Angger
Angger

Reputation: 805

Get certain key and it's value in multidimentional array in php

Suppose I have this array,

$cast = [
  'jon' => [
      'fullname' => 'Jon Snow',
      'class' => 'warrior',
   ],
   'margery' => [
      'fullname' => 'Margery Tyell',
      'class' => 'politician'
   ]
];

How do I get the key and it's certain value only? like this,

$name = ['jon'=>'Jon Snow', 'margery'=>'Margery Tyrell'];

Is there any function that support this, so It doesn't have to be loop ?

Any answer will be appreciated!

Upvotes: 0

Views: 44

Answers (2)

granit
granit

Reputation: 570

You can iterate through the multidimensional array, and add the key and the value at index fullname of the inner array in a new one-dimensional array like this:

$names = [];
foreach ($cast as $character => $character_details) {
   $names[$character] = $character_details['fullname'];
}

EDIT Alternatively, if you don't want to loop through the elements, you could use array_map function which takes a function as an argument where you can specify how to map each element of the array. In your case, you would simply return the fullname of an element.

$names = array_map(
    function ($value) {
        return $value['fullname'];
    },
    $cast
);

Upvotes: 2

lukdur
lukdur

Reputation: 129

I guess that you have iterate over it and extract only interesting you keys. Here you have an example:

function getValuesForKey($array, $key){
            $result = [];
            foreach($array as $k => $subarray){
                if(isset($subarray[$key])){
                    $result[$k] = $subarray[$key];
                }
            }
            return $result;
        }

Upvotes: 0

Related Questions