-2
stdClass Object
(
    [CountyId] => 3
    [Name] => Alba
    [Abbreviation] => AB
)
stdClass Object
(
    [CountyId] => 4
    [Name] => Arad
    [Abbreviation] => AR
)
stdClass Object
(
    [CountyId] => 5
    [Name] => Arges
    [Abbreviation] => AG
)

I want to convert this collection of stdClass Object into an array that contains only the CountyId, such as

[CountyId[0] => 3, CountyId[1] => 4, CountyId[2] => 5,...].

Anyone can help me ?

7
  • The referred answer is not very helpful. Commented Aug 18, 2016 at 7:31
  • why closed? he need something like: [CountyId[0] => 3, CountyId[0] => 4, CountyId[0] => 5,...] Commented Aug 18, 2016 at 7:31
  • Do you have an array of objects? That you want to convert into ['CountyId' => [3], 'CountyId' => [4], 'CountyId' => [5], ...]? Commented Aug 18, 2016 at 7:33
  • you cant achive this with same index for all CountryID Commented Aug 18, 2016 at 7:33
  • Exactly. It's not clear to me what the output should be. Commented Aug 18, 2016 at 7:36

1 Answer 1

0

Try this:

$array = (array)$stdClassObject;    // type casting

Update:

// convert your object into array using type casting
$array = (array) $stdClassObject;

// use array_column for specific index
$CountyIdArr = array_column($array, 'CountyId');

// note that, you can not use same index name for all values, you need to use as
$CountyIdArr['CountryID'] = $CountyIdArr;

echo "<pre>";
print_r($CountyIdArr);
Sign up to request clarification or add additional context in comments.

6 Comments

i am updating your answer.
I don't think array_column() works when the post is an object. Convert the posts to arrays first with array_map() or so?
OP already convert object into array, so i didnt use. @TorbjörnStabo
@devpro I think the array_column is what the OP is really after. This line is confusing and unnecessary: $CountyIdArr['CountryID'] = $CountyIdArr;
@Progrock: comments tell everything bro.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.