2017-09-20 73 views
-2

爲學校創建了一個多維數組。PHP:Foreach在多維數組中

<?php 
$cars = array( 
     "car1" => array ( 
      "brand" => 'BMW', 
      "license" => '30-KL-PO',  
      "price" => 10000 
      ), 

     "car2" => array (
      "brand" => 'Mercedes', 
      "license" => '51-ZD-ZD', 
      "price" => 20000 
     ), 

     "car3" => array (
      "brand" => 'Maserati', 
      "license" => 'JB-47-02', 
      "price" => 30000 
     ) 
    ); 

foreach($carss as $car){ 
echo $car['car1']['brand'] . $car['car1']['brand'] . "<br>"; 
} 

?> 

我需要使用foreach顯示所有汽車的品牌和許可證。我只用car1試過,發現錯誤:Undefined index:car1。不知道如何解決它。

我知道如何讓它顯示只使用回聲,但我的任務說我必須使用一個foreach。我根本沒有使用PHP的經驗,所以我希望你們能以正確的方式指出我。提前致謝。

回答

0

更改環路

foreach($carss as $key => $car){ 
    echo $key ." ". $car['brand'] . "<br>"; 
} 
+1

不支持offtopic問題。 – tilz0R

0

你可以做這樣的事情

<?php 
$cars = array( 
    "car1" => array ( 
     "brand" => 'BMW', 
     "license" => '30-KL-PO',  
     "price" => 10000 
    ), 
    "car2" => array (
     "brand" => 'Mercedes', 
     "license" => '51-ZD-ZD', 
     "price" => 20000 
    ), 
    "car3" => array (
     "brand" => 'Maserati', 
     "license" => 'JB-47-02', 
     "price" => 30000 
    ) 
); 
$result = []; // blank array to store result 
foreach($cars as $key => $val): 
$result[$key]["brand"] = $val["brand"]; 
$result[$key]["license"] = $val["license"]; 
endforeach; 
#echo "<pre>"; 
#print_r($result); 
?> 
0

你是爲期不遠:

<?php 
$cars = array( 
     "car1" => array ( 
      "brand" => 'BMW', 
      "license" => '30-KL-PO',  
      "price" => 10000 
      ), 

     "car2" => array (
      "brand" => 'Mercedes', 
      "license" => '51-ZD-ZD', 
      "price" => 20000 
     ), 

     "car3" => array (
      "brand" => 'Maserati', 
      "license" => 'JB-47-02', 
      "price" => 30000 
     ) 
    ); 

foreach($cars as $car) 
    printf("%-10s %s\n", $car['brand'], $car['license']); 

輸出:

BMW  30-KL-PO 
Mercedes 51-ZD-ZD 
Maserati JB-47-02 

$cars使用的密鑰針對個體值:

echo $cars['car1']['brand']; 

輸出:

BMW