需要创建一个列表,其中包含存储在特定键 (product_id) 的数组行中的所有值。目前,对 $bestsellers 变量执行 print_r 会生成以下数组:
Array
(
[0] => stdClass Object
(
[product_id] => 178
[order_item_qty] => 9
)
[1] => stdClass Object
(
[product_id] => 233
[order_item_qty] => 4
)
[2] => stdClass Object
(
[product_id] => 179
[order_item_qty] => 1
)
)
其他SO答案让我尝试:
$ids = array_column($bestsellers, 'product_id');
...但是这产生了一个空数组,我猜是因为我试图抓取的行嵌套在其中?考虑到这一点,我尝试了
foreach($bestsellers as $bestseller) {
$ids = array_column($bestsellers, 'product_id');
}
...根本没有产生任何结果。 希望有人能帮助我找出哪里出错了。谢谢!
最佳答案
嵌套值是对象,而不是数组(您在输出中看不到 stdClass Object
吗?)。 array_column
用于二维数组。您需要使用对象语法访问属性。
$ids = array_map(function($x) { return $x->product_id; }, $bestsellers);
关于php - 从特定键的嵌套数组行收集所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47294411/