2017-03-21 41 views
0
$array = array(
    "id" => array("1","2","3"), 
    "text" => array("text 1","text 2", "text 3"), 
    "checked" => array("checked","","checked") 
); 

我有一個這樣的數組。我想要像這樣訪問foreach中的值。PHP訪問多維數組然後插入值

first loop => 1 |文本1 |已檢查或爲空

second loop => 2 | text 2 |檢查或空

回答

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

此代碼可以是有用

$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|