0

I am using php 7.1 and have the following array:

enter image description here

However, I would simply like to have the following array:

array(3808, 3807, 3806, 3805)

Any suggestions how to convert it to array?

Appreciate your replies!

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Carol.Kar
  • 4,581
  • 36
  • 131
  • 264

2 Answers2

1

array_column() function will help:

$ids = array_column($records, 'ID');
print_r($ids);

Will output just array of ID's.

Check docs for it Docs

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
  • Thx! Any suggestion how to disassociate the array. I still get `0 => 3385` etc. – Carol.Kar Nov 25 '19 at 15:04
  • 1
    array_values() will return just array of values. Check it: https://www.php.net/manual/en/function.array-values.php . But 0=>3385 is ok because it is array and it should have indexes – Misha Akopov Nov 25 '19 at 15:06
  • 2
    @Anna.Klee That's how an array is shown. It just says at 0th index you have 3385. – nice_dev Nov 25 '19 at 15:07
1

Convert the Object to an Array and use array_column to return an array of values from a specific key.

$a = (object) [
    0 => [ 'ID' => 3808],
    1 => [ 'ID' => 3807],
    2 => [ 'ID' => 3806],
    3 => [ 'ID' => 3805],
];

$b = array_column((array)$a, 'ID');
// $b = [3808,3807,3806,3805]

Note: (array)$a enforces Array conversion. Conversely, (object)$a will convert an Array to a stdClass Object.

seantunwin
  • 1,698
  • 15
  • 15
  • 1
    Apparently, the `(array)$a` seems redundant in PHP's context. – nice_dev Nov 25 '19 at 15:09
  • 1
    @vivek_23 If the first parameter in `array_column` is an Object you will get the error, 'array_column() expects parameter 1 to be array, object given in...'. You must convert an Object to an Array to use `array_column`. – seantunwin Nov 25 '19 at 15:12
  • I do know that. I said from OP's point of view and since he has an array of objects, the conversion again to an array is not needed. I meant more in terms of array_column() functioning since it usually deals with array of arrays instead of array of objects and correctly understands that `ID` is a property of an object that exists and not some key in an array. – nice_dev Nov 25 '19 at 15:30
  • Bingo. It does check that via a switch case as [shown here](https://github.com/php/php-src/blob/master/ext/standard/array.c#L4222). – nice_dev Nov 25 '19 at 15:31
  • 1
    @vivek_23 I get you now. My mistake -- I misread the image as the other way around -- Object of Arrays, not Array of Objects as stated in the question. – seantunwin Nov 25 '19 at 15:35