MeltingDog
MeltingDog

Reputation: 15458

Is there a PHP function like array_column that only returns single values?

I am looping through instances of associative arrays (these associative arrays themselves are part of an array).

For each array I want to return a value, based on a key.

Currently I have:

$image_path = array_column($myarray, 'uri');

But of course array_column stores its values in a array, which, considering it's only returning 1 value, is useless to me.

Is there an existing function that will allow me to just get a value based off a supplied key?

Eg:

$image_path = get_keys_value($myarray, 'uri');

Example array. This is a very basic example. The real thing has many levels to it:

$myarray = array
  (
    'instance' => array(
      'type' => 'somedata',
      'content' => somedata',
      'image' => array(
         'name' => 'photo',
         'uri' => 'path/to/file.png'
      ),
    ),
  );

Desired outcome:

$image_path contains 'path/to/file.png' string.

Upvotes: 0

Views: 318

Answers (2)

Sergey Chizhik
Sergey Chizhik

Reputation: 617

I guess you can use array_map.

Ex:

$arr = [
    [
        'root' => [
            'child1' => [
                'child2' => 123
            ]
        ]
    ],
    [
        'root' => [
            'child1' => [
                'child2' => 456
            ]
        ]
    ],
    [
        'root' => [
            'child1' => [
                'child2' => 789
            ]
        ]
    ],
    [
        'root' => [
            'child1' => [
                'child2' => 123
            ]
        ]
    ],
];

print_r(array_map(function($row) {
    // here goes expression to get required path
    return $row['root']['child1']['child2'];
}, $arr));

Output:

Array
(
    [0] => 123
    [1] => 456
    [2] => 789
    [3] => 123
)

Upvotes: 0

Rahul
Rahul

Reputation: 18567

Try this,

function array_column_recursive(array $haystack, $needle)
{
    $found = [];
    array_walk_recursive($haystack, function ($value, $key) use (&$found, $needle) {
        if ($key == $needle) {
            $found[] = $value;
        }
    });
    return $found;
}
echo array_column_recursive($myarray, 'uri')[0];

Here is working code.

array_column will work with only 2 level array structure.

Above array will solve your problem.

I hope this will help

Upvotes: 1

Related Questions