[英]How do i add values of a certain key from two arrays into one new array in PHP?
I need to amalgamate some notices into an overall array. 我需要将一些通知合并为一个整体。
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'
);
I want to have a new array called $general_notice which merges the $today['notice'] with $general['notice']. 我想要一个名为$ general_notice的新数组,该数组将$ today ['notice']与$ general ['notice']合并。
I can't understand what to do using operators or array_merge as i only one to merge the data of a particular key... 我不明白使用运算符或array_merge做什么,因为我只有一个来合并特定键的数据...
NB $general may have multiple rows ie multiple notices... 注意:$ general可能有多行,即多条通知...
I think i cant use array_merge because the arrays are multi-dimensional. 我想我不能使用array_merge因为数组是多维的。
EG: 例如:
//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");
The desired result is: 理想的结果是:
$notices = ("Visitor arrives at 3pm", "Fire Alarms Tested This Week", "Blue Shift Working");
Since you are using arrays with keys and each array can't have duplicate keys, your desired result would be as simple as: 由于您使用带有键的数组,并且每个数组不能有重复的键,因此所需的结果将很简单:
array general_notice = array($today['notice'], $general['notice']);
unless you have a two dimensional array of arrays, for example: 除非您具有二维数组数组,例如:
array general = array(
array(
'keya' => '11',
'keyb' => 'string',
'notice' => 'Visitor Arrives at 3pm',
'keyd' => '44'
),
array(
'keya' => '1',
'notice' => 'Fire Alarms Tested This Week'
),
...
);
In that case, you would need to loop though the notices array and push desired values to a new one like so. 在这种情况下,您将需要遍历notices数组,然后将所需的值推入一个新值。 You can repeat the loop for each array you want to append to the
general_notice
array: 您可以为要附加到
general_notice
数组的每个数组重复循环:
array general_notice = array();
foreach ($general as $value) {
array_push($general_notice, $value['notice'] );
}
You can also append any single dimensional arrays as follows 您还可以按如下所示附加任何一维数组
array_push($general_notice, $today['notice']);
The question is unclear, what do you mean by merging them? 问题尚不清楚,将它们合并意味着什么? Are you trying to concatenate the values of the keys based on both arrays having the same key?
您是否尝试根据具有相同键的两个数组来串联键的值?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.