如何获得多维数组中的第一个键

时间:2014-05-30 08:25:39

标签: php arrays

$data = Array (
    [First item] => Array (
        [0] => Array (
            [1] => 2
            [2] => 2
            [3] => 2
            [4] => 2
        )
        [1] => Array (
            [1] => 2
            [2] => 2
            [3] => 2
            [4] => 2
        )
    )
    [Second Item] => Array (
       [0] => Array (
            [1] => 2
            [2] => 2
            [3] => 2
            [4] => 2
        )
    )
) 

如何回显第一个键First ItemSecond Item

   foreach($data as $value):
        echo 'This will print First Item / Second Item';

       foreach($value as $vals):

       echo $vals[1]; //so on...
       endforeach;

   endforeach;

3 个答案:

答案 0 :(得分:6)

foreach($data as $key=>$val){
  echo $key;
}

答案 1 :(得分:0)

很难确切地知道你在问什么,但这是一种递归显示所有键的方法。

<?
$data = Array (
    'First item' => Array (
        '0' => Array (
            '1' => 2,
            '2' => 2,
            '3' => 2,
            '4' => 2
        ),
        '1' => Array (
            '1' => 2,
            '2' => 2,
            '3' => 2,
            '4' => 2
        )
    ),
    'Second Item' => Array (
       '0' => Array (
            '1' => 2,
            '2' => 2,
            '3' => 2,
            '4' => 2
        )
    )
) ;

displayKeys($data);

function displayKeys($d) {
    foreach($d as $k=>$value) {
        echo "$k\n";
        if (is_array($value)) {
            displayKeys($value);
        }
    }
}

答案 2 :(得分:0)

foreach($data as $d=>$t){
echo $d;
foreach ($t as $array)

    foreach($array as $value)
        echo $value;}