2013-10-17 33 views
0

數組我有看起來像這樣:如何在多維數組中調用數組ID?

$items = array(); 
$items["GB225"] = array (
    "name" => "AAA", 
    "img" => "aaa.jpg", 
    "includes" => array(
     $things[08] = array (
       "name" => "xxx", 
       "text" => "xxxx xx xxxx x x x xxx x x" 
     ); 
     $things[77] = array (
       "name" => "yyy", 
       "text" => "yyyyyy yy yyyyyy y yy yyyyy" 
     ) ; 
     $things[42] = array (
       "name" => "zzz", 
       "text" =>"zz zzzz zzz z z zzz z" 
     ); 
    ); 
); 

我需要得到的是ID和名稱每個第二數組元素的(我需要在ID = 08 XXX,與ID = 77 YYY, zzz與ID = 42)最好使用PHP。

我最好的猜測至今一直

foreach ($items["includes"] as $thing_id => $thing) { 
    echo $thing["name"]; 
    echo $thing_id; 
}; 

但這只是給了我ID的0,1,並與「名」相關的2。

如何正確執行此操作?

+2

改變'$事情[08] = array'到'8 => array'(廣告等) – pNre

+0

通過時將它們存儲陣列中不刪除鍵(你的陣列例子呢不編譯,也許提供_actual_數組的'var_dump')。 – Wrikken

+0

$ things數組是更大的獨立$ things數組的一部分,其中包含許多未列出的$ things元素。在$ items數組中,我沒有像所示那樣實際定義$ things數組(差通信,我的錯誤),而是在之前列出的$ things數組中定義它們,並僅在$ items數組中顯示爲$ things [08 ],$東西[77],$東西[42]。 – Clik

回答

1

腳本中的$ things變量是什麼?這個變量似乎沒有被初始化。

你的代碼看起來應該像

<?php 
$items["GB225"] = array (
    "name" => "AAA", 
    "img" => "aaa.jpg", 
    "includes" => array(
     8 => array (
       "name" => "xxx", 
       "text" => "xxxx xx xxxx x x x xxx x x" 
     ), 
     77 => array (
       "name" => "yyy", 
       "text" => "yyyyyy yy yyyyyy y yy yyyyy" 
     ), 
     42 => array (
      "name" => "zzz", 
       "text" =>"zz zzzz zzz z z zzz z" 
     ) 
    ) 
); 

foreach ($items['GB225']["includes"] as $thing_id => $thing) { 
    echo $thing["name"]; 
    echo $thing_id; 
} 

看看這裏演示https://eval.in/55194

0

這是你的代碼看起來應該像:

<?php 
$items = array(); 
$items["GB225"] = array (
    "name" => "AAA", 
    "img" => "aaa.jpg", 
    "includes" => array(
     8 => array (
       "name" => "xxx", 
       "text" => "xxxx xx xxxx x x x xxx x x" 
     ), 
     77 => array (
       "name" => "yyy", 
       "text" => "yyyyyy yy yyyyyy y yy yyyyy" 
     ), 
     42 => array (
       "name" => "zzz", 
       "text" =>"zz zzzz zzz z z zzz z" 
     ) 
    ) 
); 
echo "<pre>"; 
print_r($items); 

方法1:

foreach ($items as $key => $val) { 
    foreach ($val as $key => $anArr) { 
    if ($key == "includes") { 
     foreach ($anArr as $key => $val) { 
     echo $key . " : " . $anArr[$key]['name']; 
     } 
    } 
    } 
} 

方法2:

foreach ($items['GB225']["includes"] as $thing_id => $thing) { 
    echo $thing["name"]; 
    echo $thing_id; 
}