Search code examples
phparraysmultidimensional-arrayrowarray-column

Collect all values from nested array row of specific key


Need to create a list that consists of all values stored in the array row of a specific key (product_id). Currently, doing a print_r of my $bestsellers variable produces the following array:

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
        )
  )

Other SO answers led me to try:

$ids = array_column($bestsellers, 'product_id');

...but that produced an empty array, I guess because the row I’m trying to grab is nested in there? With that in mind I tried

foreach($bestsellers as $bestseller) {
    $ids = array_column($bestsellers, 'product_id');
}

...which produced no result at all. Hopefully someone can help clue me in as to where I’m going wrong. Thanks!


Solution

  • The nested values are objects, not arrays (can't you see stdClass Object in the output?). array_column is for 2-dimensional arrays. You need to access the properties using object syntax.

    $ids = array_map(function($x) { return $x->product_id; }, $bestsellers);