2015-01-02 54 views
1

有沒有從另一個數組讀取數組的方法?如何在PHP中讀取另一個數組中的數組值?

這是我的2陣列,

$productArr = [ 
    "PT" => [ 
     "cat" => [ "image" => "cat.jpg", "desc" => "blah blah"], 
     "fish"=> [ "image" => "fish.jpg", "desc" => "blah blah"], 
     "dog" => [ "image" => "dog.jpg","desc" => "blah blah"], 
    ], 
    "KC" => [ 
     "Ice" => [ "image" => "ice.jpg", "desc" => "mah mah mah"], 
     "cold"=> [ "image" => "cold.jpg", "desc" => "mah mah mah"], 
     "water"=> [ "image" => "water.jpg", "desc" => "mah mah mah"], 
    ], 

]; 

$featuredArr = [ 
    "KC" => "Ice", 
    "PT" => "cat", 
]; 

例如,來自$featuredArr 「冰」 將與$productArr 「冰」 的鏈接,以產生 「DESC」 和 「圖像」。

+0

只是使用該值作爲鍵,它們存在於另一方面,只要添加一個isset或數組鍵存在如果你想檢查一下,檢查下面的答案 – Ghost

回答

0

使用此:

$code = "KC"; 
$product = $productArr[$code][$featuredArr[$code]]; 
echo $product['image']; 
echo $product['desc']; 
0

試試這個:

foreach($featuredArr as $key=>$val) 
    if($productArr[$key][$val]) 
     print_r($productArr[$key][$val]); 
0
$productArr = [ 
    "PT" => [ 
     "cat" => [ "image" => "cat.jpg", "desc" => "blah blah"], 
     "fish"=> [ "image" => "fish.jpg", "desc" => "blah blah"], 
     "dog" => [ "image" => "dog.jpg","desc" => "blah blah"], 
    ], 
    "KC" => [ 
     "Ice" => [ "image" => "ice.jpg", "desc" => "mah mah mah"], 
     "cold"=> [ "image" => "cold.jpg", "desc" => "mah mah mah"], 
     "water"=> [ "image" => "water.jpg", "desc" => "mah mah mah"], 
    ], 

]; 

$featuredArr = [ 
    "KC" => "Ice", 
    "PT" => "cat", 
]; 

foreach ($featuredArr as $key => $value) { 
    if ($productArr[$key][$value]) { 
     echo "key $key=>$value exists: <br />"; 
     foreach ($productArr[$key][$value] as $newKey => $newValue) { 
     echo "$newKey :: $newValue <br />"; 
     } 
    } 
} 

輸出:

key KC=>Ice exists: <br />image :: ice.jpg <br />desc :: mah mah mah <br />key PT=>cat exists: <br />image :: cat.jpg <br />desc :: blah blah <br /> 

請注意,它在很大程度上取決於什麼用,你必須做的你的鑰匙和你的價值觀:使用上面的代碼你可以通過將所需的key =>值對添加到$ featuredArr數組中,通過數組循環遍歷數組。

希望這會有所幫助。

+0

我有一個問題呼應出圖像,你有一個問題解決方案? – Jun

+0

什麼樣的問題?迴應圖像或正確顯示它?打印標籤時務必檢查圖像的確切路徑。 – briosheje

相關問題