PHP Access Multidimensional Array然后插入值

时间:2017-03-21 21:52:02

标签: php arrays multidimensional-array

$array = array(
  "id" => array("1","2","3"), 
  "text" => array("text 1","text 2", "text 3"), 
  "checked" => array("checked","","checked")
);

我有这样的数组。我想在foreach中访问这样的价值。

first loop => 1 |文字1 |选中或null

second loop => 2 |文字2 |选中或null

2 个答案:

答案 0 :(得分:1)

foreach($array['id'] as $key=>$value)
{

    echo $value . ' | ' . $array['text'][$key] . ' | ' . ($array['checked'][$key] == 'checked' ? 'checked' : 'null') . '<br />';

}

<强>结果:

1 | text 1 | checked
2 | text 2 | null
3 | text 3 | checked

答案 1 :(得分:1)

此代码非常有用

$array = array(
  "id" => array("1","2","3"), 
  "text" => array("text 1","text 2", "text 3"), 
  "checked" => array("checked","","checked")
);

// find the max count of multidimensional arrar
$count = max( array_map( 'count',  $array ) );
for($i=0;$i<$count;$i++){
    foreach($array as $key=>$value){
        echo $array[$key][$i]."|";

    }
     echo "\n";
}

输出:

1|text 1|checked|
2|text 2||
3|text 3|checked|