[英]how to append element to array with specific index in php
我是 php 的新手。 我正在嘗試獲取特殊數組中每個元素的鍵和值。 我想從零索引開始將它們保存/推送到另一個數組中。 當然(foreach 循環)是這里最好的工具。 請按您的代碼幫助我。 我知道描述這個問題有點困難,所以我有一些圖紙給你。
$info = array(
<--key--> <--value-->
[10] => 'apple',
[8] => 'orange',
[2] => 'banana',
[23] => 'peach',
)
now I want to have an array like this:
$myGoal = array(
<-key-> <--------value--------->
[0] => array('10'=>'apple'),
[1] => array('8'=>'orange'),
[2] => array('2'=>'banana'),
[3] => array('23'=>'peach')
)
我想我需要的代碼應該如下所示:
$info = array(
[10] => 'apple',
[8] => 'orange',
[2] => 'banana',
[23] => 'peach',
)
$index = 0;
$myGoal = array();
foreach($info as $amount => $friut){
$myGoal[$index] = [$amount][$friut];
$index++;
}
我會感謝任何可以幫助我的人。
關於語法$myGoal[$index] = [$amount][$friut];
等號之后的部分是創建一個具有單個值$amount
的數組,然后嘗試使用不存在的$friut
值對數組進行索引。
您可以更新語法以使用key => value
將數組添加到索引
改變
$myGoal[$index] = [$amount][$friut];
至
$myGoal[$index] = [$amount => $friut];
Output
Array
(
[0] => Array
(
[10] => apple
)
[1] => Array
(
[8] => orange
)
[2] => Array
(
[2] => banana
)
[3] => Array
(
[23] => peach
)
)
正如@kaczmen指出的那樣,如果你只想 append 你不需要索引,你可以使用
$myGoal[] = [$amount => $friut];
您可以使用array_chunk
使用塊大小為 1 來執行此操作。
$myGoal = array_chunk($info, 1, true);
請務必將第三個參數設置為true
以保留密鑰。
此外,與您的要求沒有直接關系,但我想建議使用 amount 作為數組鍵是有風險的。 如果您有相同數量的兩個項目,第二個將覆蓋第一個。
首先初始化一個數組,然后將鍵值存儲到一個新數組中。
$info = array("10" => 'apple',"8" => 'orange',"2" => 'banana',"23" => 'peach');
$new=array();
foreach($info as $key=>$info1)
{
$new[] = [$key=>$info1];
}
echo "<pre>";
print_r($new);
希望這可以幫助。
你可以使用array_walk
,如果你想從 0 開始,你不需要聲明$index=0
0
。 您可以只使用$n[]
它會自動從0
索引開始
array_walk($info,function($v,$k)use(&$n){$n[]=[$k=>$v];});
print_r($n);
工作示例:- https://3v4l.org/DTACm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.