从多维数组中获取值

时间:2013-03-21 18:17:27

标签: php json multidimensional-array

我有一个脚本,它以下列格式创建一个数组

  $named_array["vehicles"][0]['vehicle'] = "i100-1 "  ;
  $named_array["vehicles"][1]['vehicle'] = "i100-2 "  ;
  $named_array["vehicles"][2]['vehicle'] = "i100-46 "  ;

我想在稍后的脚本中做的是从$ named_array获取索引值[0-1-2 etc] 但我只有值(i100-1等)作为查询选项,这样我以后可以改变它。我想要实现的是,$named_array的索引值是什么,其中值为i100-2

这是最后输出到json。

我希望这是有道理的!有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

function complex_index_of($named_array, $val){
    for($i=0, $n=count($named_array['vehicles']); $i<$n; $i++){
        if ($named_array['vehicles'][$i]['vehicle'] == $val)
            return $i;
    }
    return -1;
}


echo complex_index_of($named_array, 'i100-2 ');
// output: 1

答案 1 :(得分:1)

尝试类似这样的事情(如果您需要多次创建,可以创建一个函数)

$needle = 'i100-1';
$vIndex = -1;
foreach ($named_array["vehicles"] as $index => $data) {
    if($data['vehicle'] == $needle) {
        $vIndex = $index;
        break;
    }
}