查找数组键并在php中获取值

问题描述 投票:0回答:1

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 arrays multidimensional-array
1个回答
1
投票

嗯,我认为您的解决方案还不错。但这可能有助于您提高其可读性:

<?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 
© www.soinside.com 2019 - 2024. All rights reserved.