joomla / virtuemart /可存储的自定义字段
我有一个多维数组(virtuemart $ product),我想获取子产品(和array_sum)的库存值。
有更简单的方法吗?位置也可能会改变。类似于find_key-> get array_sum
if (array_key_exists('customfieldsSorted', $product)) {
echo array_sum(array_column(
$product->customfieldsSorted['addtocart'][0]->stockableCombinations->combinations,
'stock'
));
}
//return 999 - this is the value I need
//array
if (array_key_exists('customfieldsSorted', $product)) {
print_r($product->customfieldsSorted['addtocart'][0]->stockableCombinations->combinations);
}
//return
Array
(
[0] => Array
(
[product_id] => 72
[customfield_ids] => Array
(
[0] => 13
)
[stock] => 99
)
[1] => Array
(
[product_id] => 73
[customfield_ids] => Array
(
[0] => 14
)
[stock] => 99
)
[n] => Array
(......)
)
嗯,我认为您的解决方案还不错。但这可能有助于您提高其可读性:
<?php declare(strict_types=1);
function sumColumns(array $list, string $column): int {
return array_sum(array_column($list, $column));
}
function sumStock(array $fields): int {
$list = $fields[0]->stockableCombinations->combinations;
return sumColumns($list, 'stock');
}
// Usage example:
$combinations = new \stdClass();
$combinations->combinations = [
['stock' => 10],
['stock' => 20]
];
$cart = new \stdClass();
$cart->stockableCombinations = $combinations;
$product = new \stdClass();
$product->customfieldsSorted = ['addtocart' => [$cart]];
$stock = 0;
if (isset($product->customfieldsSorted['addtocart'])) {
$stock = sumStock($product->customfieldsSorted['addtocart']);
}
//$stock === 30