如何使用foreach获取PHP中数组的索引号?

时间:2012-08-13 21:51:51

标签: php arrays foreach

我正在尝试解析电视节目API中的数据,但我无法弄清楚如何获取索引编号。

示例:

{
"data": {
    "0": {
        "1": {
            "param1": "value1", 
            "param2": "warning", 
        }
    }, 
    "1": {
        "1": {
            "param1": "value1", 
            "param2": "value2", 
        }, 
        "2": {
            "param1": "value1", 
            "param2": "warning", 
        }, 
        "3": {
            "param1": "value1", 
            "param2": "warning", 
        }, 
    }
}
}

“params”和“values”我能够很好地完成,但我不能“回应”索引号。

这就是我尝试这样做的方式:

$string = file_get_contents(api);
$json_a = json_decode($string, true);
foreach ($json_a['data'] as $seasons) {
    foreach ($seasons as $episodes) {
            if ($episodes['param2']=="warning") {
            // echo index number of season
            // echo index number of episode

            }
    }
}

我相信我已经读过使用foreach我无法获得索引号码?如果是这样,解决方案是什么?

我尝试“手动”增加季节数和剧集的变量,但索引号可能会有所不同。它们可能不是顺序的,有些以索引“1”而不是“0”开始。

4 个答案:

答案 0 :(得分:1)

使用foreach (array_expression as $key => $value)代替foreach (array_expression as $value)$key就是您所缺少的。

PHP: foreach

答案 1 :(得分:1)

您不需要计数器,只需在foreach

的定义中添加密钥即可

例如。

$test = array('foo' => 'bar');

foreach($test as $key => $value) {
    echo $key . "\n";
    echo $value;
}

输出

foo
bar

http://php.net/manual/en/control-structures.foreach.php

答案 2 :(得分:0)

试试这个:

foreach ($json_a['data'] as $index1 => $seasons) {}

同样地:

foreach ($seasons as $index2 => $episodes) {}

答案 3 :(得分:0)

我无法对你的json进行编码,但

使用了如下数组:

array
  0 => 
    array
      1 => 
        array
          'param1' => string 'value1' (length=6)
          'param2' => string 'warning' (length=7)
  1 => 
    array
      1 => 
        array
          'param1' => string 'value1' (length=6)
          'param2' => string 'warning' (length=7)
      2 => 
        array
          'param1' => string 'value1' (length=6)
          'param2' => string 'value2' (length=6)

这是代码:

$a[0][1] = array("param1"=>"value1","param2"=>"warning");
$a[1][1] = array("param1"=>"value1","param2"=>"warning");
$a[1][2] = array("param1"=>"value1","param2"=>"value2");

foreach($a as $key=>$val)
{
    foreach($val as $skey => $sval)
    {
        if($sval['param2']=="warning")
            echo $key."-".$skey."<br>";
    }
}