php - 从特定键的嵌套数组行收集所有值

标签 php arrays multidimensional-array row array-column

需要创建一个列表,其中包含存储在特定键 (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/

相关文章:

在 DataTables $columns 数组中使用 date_diff() 函数时出现 PHP 错误

C 程序 - 取消引用指针

php - MySQL > 仅比较和报告某些行的时间差异

php - joomla 1.5 间歇性错误上的 Smartformer 组件

PHP 监控我的所有应用程序和网站的错误、日志等

php - 接受有效 float 的正则表达式 [PHP]

javascript - 当数组较大时,为什么此函数返回 {author : Robert C. Martin, likes: NaN}

c - 我的程序将第一个数组元素设置为 NUM_EL 而不是随机数,但其余元素随机生成

Python 将嵌套 for 循环转换为初始化理解

php - 在 PHP 中从多个数组创建多维数组