Проблемы с php array_filter, попытка получить данные, но это не работаетPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Проблемы с php array_filter, попытка получить данные, но это не работает

Сообщение Anonymous »

Я новичок в PHP и пытаюсь разобраться в array_filter и понять, почему он у меня не работает.
У меня есть большой массив из песочницы namecheap для тестирования и изучения. от моего коллеги.
Итак, я передаю массив и указанный домен TLD в свою функцию и ожидаю, что из «регистра» будет возвращена одна цена. категория продукта.

Код: Выделить всё

class registerPrice {
function getRegisterPrice($domainTLD, $newArr) {
// Extract the "Register" product category for the target TLD
$registerCategory = array_filter($newArr['CommandResponse']['UserGetPricingResult']['ProductType'], function ($category) use ($domainTLD) {
return $category['@attributes']['Name'] === 'register' && $category['Product']['@attributes']['Name'] === $domainTLD;
});

// Extract the prices for the 1-year duration from the "register" category for the target TLD
$registerPrices = array_column($registerCategory, 'Product');
$registerPriceForOneYear = null;
foreach ($registerPrices as $product) {
foreach ($product as $price) {
if ($price['@attributes']['Duration'] == 1 && $price['@attributes']['DurationType'] == 'YEAR') {
$registerPriceForOneYear = $price['Price']['@attributes']['Price'];
break 2; // Exit both loops once the price for 1 year is found
}
}
}
return $registerPriceForOneYear;
}
}
Часть используемого мной массива:

Код: Выделить всё

Array
(
[@attributes] => Array
(
[Status] => OK
)

[Errors] => Array
(
)

[Warnings] => Array
(
)

[RequestedCommand] => namecheap.users.getpricing
[CommandResponse] => Array
(
[@attributes] => Array
(
[Type] => namecheap.users.getPricing
)

[UserGetPricingResult] => Array
(
[ProductType] => Array
(
[@attributes] => Array
(
[Name] => domains
)

[ProductCategory] => Array
(
[0] => Array
(
[@attributes] => Array
(
[Name] => reactivate
)

[Product] => Array
(
[@attributes] => Array
(
[Name] => com
)

[Price] => Array
(
[@attributes] => Array
(
[Duration] => 1
[DurationType] => YEAR
[Price] => 13.48
[PricingType] => MULTIPLE
[AdditionalCost] => 0.18
[RegularPrice] => 15.88
[RegularPriceType] => MULTIPLE
[RegularAdditionalCost] => 0.18
[RegularAdditionalCostType] => MULTIPLE
[YourPrice] => 13.48
[YourPriceType] => MULTIPLE
[YourAdditonalCost] => 0.18
[YourAdditonalCostType] => MULTIPLE
[PromotionPrice] => 0.0
[Currency] =>  USD
)

)

)

)

[1] => Array
(
[@attributes] => Array
(
[Name] => register
)

[Product] => Array
(
[@attributes] => Array
(
[Name] => com
)

[Price] => Array
(
[0] => Array
(
[@attributes] => Array
(
[Duration] => 1
[DurationType] => YEAR
[Price] => 10.28
[PricingType] => ABSOLUTE
[AdditionalCost] => 0.18
[RegularPrice] => 13.98
[RegularPriceType] => MULTIPLE
[RegularAdditionalCost] => 0.18
[RegularAdditionalCostType] => MULTIPLE
[YourPrice] => 10.28
[YourPriceType] => ABSOLUTE
[YourAdditonalCost] => 0.18
[YourAdditonalCostType] => MULTIPLE
[PromotionPrice] => 0.0
[Currency] => USD
)

)

Я постоянно получаю неопределенную ошибку ключа массива всякий раз, когда запускаю это.
Я знаю, что данные определенно существуют, потому что я могу «жестко запрограммировать» их следующим образом:

Код: Выделить всё

$domainRegistration = $newArr['CommandResponse']['UserGetPricingResult']['ProductType']['ProductCategory']['2']['Product']['Price']['0']['@attributes']['Price'];
Полная информация об ошибке находится здесь:

Код: Выделить всё

PHP Warning:  Undefined array key "@attributes" in D:\xampp\htdocs\sm\registrationPrice.php on line 6

Warning: Undefined array key "@attributes" in D:\xampp\htdocs\sm\registrationPrice.php on line 6

Warning: Trying to access array offset on value of type null in D:\xampp\htdocs\sm\registrationPrice.php on line 6

Warning: Undefined array key "@attributes" in D:\xampp\htdocs\sm\registrationPrice.php on line 6

Warning: Trying to access array offset on value of type null in D:\xampp\htdocs\sm\registrationPrice.php on line 6
строка 6:

Код: Выделить всё

return $category['@attributes']['Name'] === 'register' && $category['Product']['@attributes']['Name'] === $domainTLD;


Подробнее здесь: https://stackoverflow.com/questions/783 ... ot-working
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»