Reputation: 169
joomla/virtuemart/stockable custom fields
I have a multidimensional array (virtuemart $product) and I want to get stock values of child products (and array_sum).
is there an easier way to do this? position may also change. Something like 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
(......)
)
Upvotes: 0
Views: 52
Reputation: 2011
Well, I think your solution wasn't bad. But this might help you to improve its readability:
<?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:
/** This works as a "fixture function" to create a class with some data */
function newProduct(): \stdClass {
$combinations = new \stdClass();
$combinations->combinations = [['stock' => 10],['stock' => 20],/*...*/];
$cart = new \stdClass();
$cart->stockableCombinations = $combinations;
$product = new \stdClass();
$product->customfieldsSorted = ['addtocart' => [$cart]];
return $product;
}
$product = newProduct();
$stock = 0;
if (isset($product->customfieldsSorted['addtocart'])) {
$stock = sumStock($product->customfieldsSorted['addtocart']);
}
var_dump($stock); //$stock === 30
Upvotes: 2