user1899415
user1899415

Reputation: 3125

php: getting only top value in multidimensional array

My nested array looks like:

[Minion] => Array
    (
        [old_first_name] => "\345\205\265"
        [old_last_name] => "\345\274\265"
        [old_name] => "\345\205\265\345\274\265"
    )

[Evil Minion] => Array
    (
        [old_first_name] => "\347\251\216"
        [old_last_name] => "\345\274\265"
        [old_name] => "\345\274\265\347\251\216"
    )

[Minion 2] => Array
    (
        [old_first_name] => "\345\212\233"
        [old_last_name] => "\345\274\265"
        [old_name] => "\345\274\265\345\212\233"
    )

How do I just get Minion, Evil Minion, and Minion 2?

I tried a for loop but it's just looping through the contents of Minion which isn't what I want!

Upvotes: 0

Views: 49

Answers (3)

verisimilitude
verisimilitude

Reputation: 5108

You'd be interested in array_keys to just fetch the keys...

$keys = array_keys($arr);

Since this returns an array of the keys, you may further loop through it using a for-each construct.

Upvotes: 0

Do this way.. you need to nest furthermore

<?php
$arr= array(

    'Minion' => Array
    (
        'old_first_name' => "\345\205\265",
        'old_last_name' => "\345\274\265",
        'old_name' => "\345\205\265\345\274\265"
    ),

    'Evil Minion' => Array
    (
        'old_first_name' => "\347\251\216",
        'old_last_name' => "\345\274\265",
        'old_name' => "\345\274\265\347\251\216"
    ),

    'Minion 2' => Array
    (
        'old_first_name' => "\345\212\233",
        'old_last_name' => "\345\274\265",
        'old_name' => "\345\274\265\345\212\233"
    )
);

foreach($arr as $arr1)
{
    foreach($arr1 as $k=>$v)
    {
        echo "$k => $v";
    }
}

Demo

Upvotes: 0

Barmar
Barmar

Reputation: 781592

Use the array_keys function:

$keys = array_keys($array);
var_dump($keys);

This works for any array, whether it's one-dimensional or multi-dimensional.

Upvotes: 1

Related Questions