![](/img/trans.png)
[英]How do I combine two arrays, one as a key and the other as an array?
[英]How do i add values of a certain key from two arrays into one new array in PHP?
我需要將一些通知合並為一個整體。
array today = array(
'keya' => '11',
'keyb' => 'string',
'notice' => 'Visitor Arrives at 3pm',
'keyd' => '44',
...
);
array general = array(
'keya' => '1',
'notice' => 'Fire Alarms Tested This Week'
);
我想要一個名為$ general_notice的新數組,該數組將$ today ['notice']與$ general ['notice']合並。
我不明白使用運算符或array_merge做什么,因為我只有一個來合並特定鍵的數據...
注意:$ general可能有多行,即多條通知...
我想我不能使用array_merge因為數組是多維的。
例如:
//1st array with lots of data but the data belonging to the 'notice' key is what i'm interested in.
array $today = [0]('id'=>'1','lotsOfKeys'=>"lots of values,'notice'="Visitor arrives at 3pm");
array $general = [0]('id'=> '1', 'notice' = "Fire Alarms Tested This Week"),
[1]('id'=> '2', 'notice' = "Blue Shift working");
理想的結果是:
$notices = ("Visitor arrives at 3pm", "Fire Alarms Tested This Week", "Blue Shift Working");
由於您使用帶有鍵的數組,並且每個數組不能有重復的鍵,因此所需的結果將很簡單:
array general_notice = array($today['notice'], $general['notice']);
除非您具有二維數組數組,例如:
array general = array(
array(
'keya' => '11',
'keyb' => 'string',
'notice' => 'Visitor Arrives at 3pm',
'keyd' => '44'
),
array(
'keya' => '1',
'notice' => 'Fire Alarms Tested This Week'
),
...
);
在這種情況下,您將需要遍歷notices數組,然后將所需的值推入一個新值。 您可以為要附加到general_notice
數組的每個數組重復循環:
array general_notice = array();
foreach ($general as $value) {
array_push($general_notice, $value['notice'] );
}
您還可以按如下所示附加任何一維數組
array_push($general_notice, $today['notice']);
問題尚不清楚,將它們合並意味着什么? 您是否嘗試根據具有相同鍵的兩個數組來串聯鍵的值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.