Я новичок в 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;
Привет, спасибо, да, я сделал. Я пробовал так много раз, что внес больше ошибок. Судя по тому, что я видел, если я добавлю [productCategory] обратно, я верну свою первоначальную проблему, которая заключается в том, что он, похоже, не может найти данные и установить их в переменную. Есть идеи, почему кажется, что он возвращает пустой массив, когда есть данные, которые ему соответствуют?
пожалуйста, опубликуйте массив в формате json, чтобы мы могли запустить на нем тест.
Вот пастабин со всем XML-кодом в формате JSON: astebin.com/ZxHJei6i
Фильтр должен закончиться $newArr['CommandResponse']['UserGetPricingResult']['ProductType']['ProductCategory']
.
Внутренний цикл foreach
должен завершиться $product['Price']
, а не $product
.
function getRegisterPrice($domainTLD, $newArr) {
// Extract the "Register" product category for the target TLD
$registerCategory = array_filter($newArr['CommandResponse']['UserGetPricingResult']['ProductType']['ProductCategory'], function ($category) use ($domainTLD) {
//var_dump($category);
$catName = $category['@attributes']['Name'];
$prodName = $category['Product']['@attributes']['Name'];
//echo "Cat: $catName\nProduct: $prodName\n";
return $catName === 'register' && $prodName === $domainTLD;
});
//var_dump($registerCategory);
// Extract the prices for the 1-year duration from the "register" category for the target TLD
$registerPrices = array_column($registerCategory, 'Product');
var_dump($registerPrices);
$registerPriceForOneYear = null;
foreach ($registerPrices as $product) {
foreach ($product['Price'] as $price) {
if ($price['@attributes']['Duration'] == 1 && $price['@attributes']['DurationType'] == 'YEAR') {
$registerPriceForOneYear = $price['@attributes']['Price'];
break 2; // Exit both loops once the price for 1 year is found
}
}
}
return $registerPriceForOneYear;
}
Для первого параметра
array_filter()
вы забыли['ProductCategory']
в конце.