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!

3
  • 1
    please provide the code you try to Commented Nov 25, 2019 at 14:59
  • 3
    Possible duplicate of php stdClass to array Commented Nov 25, 2019 at 15:00
  • 1
    array_column($lastPostIDs, 'ID') Commented Nov 25, 2019 at 15:01

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thx! Any suggestion how to disassociate the array. I still get 0 => 3385 etc.
array_values() will return just array of values. Check it: php.net/manual/en/function.array-values.php . But 0=>3385 is ok because it is array and it should have indexes
@Anna.Klee That's how an array is shown. It just says at 0th index you have 3385.
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.

5 Comments

Apparently, the (array)$a seems redundant in PHP's context.
@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.
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.
Bingo. It does check that via a switch case as shown here.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.