我的问题需要你的帮助。我的问题是我有2个数组,第一个是主数组。第二个是我的新数据的数组。
假设我有这些数组。
这是主阵列:
Array
(
0 => Array
(
'id' => 1,
'name' => 'Apple',
'age' => 12
)
1 => Array
(
'id' => 2,
'name' => May,
'age' => 13
)
)
这是第二个数组:
Array
(
1 => Array
(
'gender' => 'Male'
)
2 => Array
(
'gender' => 'Female'
)
)
我在PHP中有这个循环
foreach($main_array as &$main){
//this is the loop inside the first array
// how can I add the second array with it?
}
这是示例输出:
[0] => Array
(
[id] => 1
[name] => Apple
[age] => 12
[gender] => Female
)
[1] => Array
(
[id] => 2
[name] => May
[age] => 13
[gender] => Female
)
我该怎么做?有什么建议?这一切都归功于。
答案 0 :(得分:3)
for($i=0; $i<count($main_array); $i++){
for($j=0; $j<count($second_array); $j++){
if($main_array[$i]['id'] == $j){
$main_array[$i]['gender'] = $second_array[$j]['gender']
}
}
}
答案 1 :(得分:1)
这些功能的确切行为需要在使用前进行研究和测试,以确保它符合您的意图。
// array merge recursive doesn't merge numeric keys
$main_array = array_merge_recursive($main_array, $secondary_array);
// array replace recursive has a downside of replacing stuff
$main_array = array_replace_recursive($main_array, $secondary_array);
foreach($main_array as $i => &$main){
if(isset($secondary_array[$i])) {
foreach($secondary_array[$i] AS $key => $value) {
$main[$key] = $value;
}
}
}
上述两种解决方案仅适用于$main_array
和$secondary_array
的数组索引匹配的情况。
在您的示例中,您的数组不匹配:
- $secondary_array[0]
不存在,因此$main_array[0]
不会填充'gender'
值;
- $main_array[2]
不存在,因此将$main_array[2]
创建'gender'
,其值只有$secondary_array[2]['gender']
foreach($main_array as $i => &$main) {
if(isset($secondary_array[$i])) and isset($secondary_array[$i]['gender'])) {
$main['gender'] = $secondary_array[$i]['gender'];
}
}
答案 2 :(得分:1)
我修复了你的示例代码,否则它不会运行。
<?php
// Test data:
$main_array = Array(
0 => Array(
'id' => 1,
'name' => 'Apple',
'age' => 12
),
1 => Array (
'id' => 2,
'name' => 'May',
'age' => 13
)
);
$lookup = Array(
1 => Array(
'gender' => 'Male'
),
2 => Array(
'gender' => 'Female'
)
);
// Your answer:
foreach ($main_array as &$main) {
if (array_key_exists($main['id'],$lookup)) {
$main['gender'] = $lookup[$main['id']]['gender']; // <-- sets gender value
}
}
// Output it to browser:
echo '<pre>$main_array = '.print_r($main_array,true).'</pre>';
当array_key_exists()
数据不完整时,PHP Notice: Undefined offset: 123
检查可以避免$lookup
之类的错误。
答案 3 :(得分:0)
foreach($main_array as &$main){//this is the loop inside the first array
foreach($second_array as &$second){ //this is the loop inside the second array
}
}
答案 4 :(得分:-1)
foreach($arr1 as $k => $arr1Item) {
$arr1[$k]['gender'] = $arr2[$k]['gender'];
}