2

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!

2 Answers2

1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • BTW, if you got this from `json_decode`, you can use a second argument of `true` to make it return a 2-dimensional array instead of an array of objects. – Barmar Nov 14 '17 at 20:24
  • 1
    I saw it just fine... but considering I'm fairly new to PHP and also saw the word Array it didn't hold much weight. This worked, thank you for the solution and explanation! – user8941305 Nov 14 '17 at 20:27
1

For future reference, array_column will work for this in PHP 7, so you must be using PHP 5.

For PHP 7, your code

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

will do what you want it to.

See the difference here on 3v4l.org.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80