我有两个数组,并希望将第一个数组中的值作为键对值添加到第二个数组。所以关键是说[topic],值是第一个数组的值。我提供了原始数组,以及我正在寻找的结果。谢谢。
Array
(
[0] => 1
[1] => 2
[2] => 1
)
Array
(
[0] => Array
(
[id] => 19
[first] => Michelle
[last] => Walters
[sun] => 1
)
[1] => Array
(
[id] => 182
[first] => Robin
[last] => Conti
[sun] => 1
)
[2] => Array
(
[id] => 183
[first] => Cheri
[last] => Constantino-Shor
[sun] => 1
)
)
这是我正在寻找的结果:
Array
(
[0] => 1
[1] => 2
[2] => 1
)
Array
(
[0] => Array
(
[id] => 19
[first] => Michelle
[last] => Walters
[sun] => 1
[topic]=> 1
)
[1] => Array
(
[id] => 182
[first] => Robin
[last] => Conti
[sun] => 1
[topic]=> 2
)
[2] => Array
(
[id] => 183
[first] => Cheri
[last] => Constantino-Shor
[sun] => 1
[topic]=> 1
)
)
答案 0 :(得分:0)
这非常简单 - 可能有一百万种方法 - 最基本的是for
循环。假设您的主题值数组被称为$topics
,而您的主数组被称为$users
:
$topics = array(1, 2, 1);
$users = array(
array(
'id' => 19,
'first' => 'Michelle',
'last' => 'Walters',
'sun' => 1,
),
array(
'id' => 182,
'first' => 'Robin',
'last' => 'Conti',
'sun' => 1,
),
array(
'id' => 183,
'first' => 'Cheri',
'last' => 'Constantino-Shor',
),
);
$count = count($users);
for ($i = 0; $i < $count; $i++) {
$users[$i]['topic'] = $topics[$i];
}
var_dump($users);
收率:
array (size=3)
0 =>
array (size=5)
'id' => int 19
'first' => string 'Michelle' (length=8)
'last' => string 'Walters' (length=7)
'sun' => int 1
'topic' => int 1
1 =>
array (size=5)
'id' => int 182
'first' => string 'Robin' (length=5)
'last' => string 'Conti' (length=5)
'sun' => int 1
'topic' => int 2
2 =>
array (size=4)
'id' => int 183
'first' => string 'Cheri' (length=5)
'last' => string 'Constantino-Shor' (length=16)
'topic' => int 1