Ramtin Gh
Ramtin Gh

Reputation: 1050

get values of certain key in multidimensional PHP array

I have an array called $arr which looks like this when I print_r($arr):

Array
(
    [0] => stdClass Object
        (
            [term_id] => 8
            [name] => name0
            [slug] => slug0
        )

    [1] => stdClass Object
        (
            [term_id] => 7
            [name] => name1
            [slug] => slug1
        )

    [2] => stdClass Object
        (
            [term_id] => 6
            [name] => name2
            [slug] => slug2
        )

)

now, I want to be able to get all the values of [name] in an array so later I can use this array to filter some data. So the output I'm looking for is something like:

array(0 => 'name0', 1 => 'name1', 2 => 'name2', 3 => 'name3');

Upvotes: 0

Views: 211

Answers (2)

chao
chao

Reputation: 2024

First: $array = (array) $arr;.

Then:

foreach($array as $a) {
    $data[] = $a['name'];
}

$data should contain array you are looking for (didn't try code but it should be ok).

Upvotes: 0

Orangepill
Orangepill

Reputation: 24645

You can use array_map (Note: This syntax requires PHP 5.3+)

$names = array_map(function($a){ return $a->name; }, $array);

Upvotes: 2

Related Questions