簡體   English   中英

循環foreach php的問題

[英]Issue with the loop foreach php

抱歉,如果我的問題看起來很愚蠢,我是 php 新手。 我嘗試在我的數組上創建一個循環,但循環只返回最后一個值。 我不明白,我嘗試了一切

$categories = array('name' => 'mamals', 'id' => '1');
$categories = array('name' => 'birds','id' => '2');
$categories = array('name' => 'fishs', 'id' => '3');
$categories = array('name' => 'reptiles', 'id' => '4');

$category = $categories;

foreach($category as $key =>$categ){
    echo $categ;
}

它只返回“爬行動物 4”! 謝謝你的回答

您正在覆蓋變量categories ,我通過使用空數組初始化categories來修改代碼,然后將您的條目推入其中。

$categories = [];
array_push($categories, array('name' => 'mamals', 'id' => '1'));
array_push($categories, array('name' => 'birds','id' => '2'));
array_push($categories, array('name' => 'fishs', 'id' => '3'));
array_push($categories, array('name' => 'reptiles', 'id' => '4'));

foreach($categories as $key=>$categ){
    echo "ID: " . $categ["id"] . ", NAME: " . $categ["name"];
}

我回復了shunz19 的回答,我說:

這也將有助於顯示該機制的簡寫。 我認為沒有人會在這種情況下使用 array_push 。

這是一個更簡潔的解決方案:

原因:

您正在覆蓋您的變量 - $categories - 每次使用= 所以在第 3 行之后, $categories中的唯一值是:

categories = array('name' => 'reptiles', 'id' => '4');

一步步:

您看起來想要條目添加到 Categories 多維數組中。 因此,您需要告訴 PHP添加not to overwrite ,通常使用[]指示將值插入到新的(增量)變量鍵中。

$categories = array('name' => 'mamals', 'id' => '1');
$categories[] = array('name' => 'birds','id' => '2');

這會將鍵索引(數字)增加 1,並將array的值設置為該鍵。

標准做法是建立數值數組,然后用這種引用方式填充它們。

但這並不簡單...

因為您的父數組包含子數組,所以您的foreach將給出警告和錯誤,因為:

警告:第 XX 行 /home/user/scripts/code.php 中的數組到字符串轉換

你能看出為什么嗎? 是的,因為您的foreach僅打開父數組,而不是子數組,因此其中的數據類型仍然是數組,但您希望將它們輸出為字符串。

你怎么能做到這一點? 有一個有趣的小函數叫做print_r()

簡潔的解決方案和修復:

$categories = []; // Establish the var type is an array.
$categories[] = array('name' => 'mamals', 'id' => '1'); // Add to the array.
$categories[] = array('name' => 'birds','id' => '2'); // add more,... 
$categories[] = array('name' => 'fishs', 'id' => '3');
$categories[] = array('name' => 'reptiles', 'id' => '4');

$category = $categories;

foreach($category as $key =>$categ){
     print_r($categ);
}

輸出:

 Array ( [name] => mamals [id] => 1 ) Array ( [name] => birds [id] => 2 ) Array ( [name] => fishs [id] => 3 ) Array ( [name] => reptiles [id] => 4 )

代碼示例:

您也可以只從 froeach 訪問數組名稱,例如:

foreach($category as $key =>$categ){
     print $categ['name']."\n"; // will list each name starting at the lowest array key. 
}

在這里查看我的測試代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM