多维数组foreach关键项php

时间:2014-01-22 16:15:12

标签: php arrays

阵列

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 17
                    [model] => SB125T-23B
                    [file] => SB125T-23B_Blue
                    [color] => Blue
                    [hex] => 0033ff-3c3c3c
                    [active] => 1
                )

            [1] => Array
                (
                    [id] => 18
                    [model] => SB125T-23B
                    [file] => SB125T-23B_Red
                    [color] => Red
                    [hex] => CC0000-3c3c3c
                    [active] => 1
                )

        )

PHP代码

foreach ($threeSixty[0] as $key => $value) { 
    foreach ($value as $k => $v) { 
        echo $threeSixty[$key][$v];
    }
}

我有这个数组和PHP代码。我试图循环外部数组来到内部数组。然后循环通过那些我试图获取文件下的数据。这样做我现在如何获得它只返回每个数据项的值。所以id然后模型等等。

我怎么能这样做,所以我可以访问该文件,所以 echo $ threeSixty [0] ['file']; ,例如。

1 个答案:

答案 0 :(得分:1)

您使用价值$v作为关键字 - 使用$k代替。此外,除非数组中的数组中有数组 - 否则不要在第一个循环中指定索引。 (我想你在数组中有一个数组: - )

foreach ($threeSixty as $key => $value) { 
    foreach ($value as $k => $v) { 
        echo $threeSixty[$key][$k];
    }
}

获得file

foreach ($threeSixty as $key => $value) { 
    echo $threeSixty[$key]['file'];
}

只获得一个file

echo $threeSixty[0]['file'];

编辑:我假设$threeSixty看起来像这样:

$threeSixty = array(
    array(
        'id' => '17',
        'model' => 'SB125T-23B',
        'file' => 'SB125T-23B_Blue',
        'color' => 'Blue',
        'hex' => '0033ff-3c3c3c',
        'active' => '1'
    )
);