I have 2 arrays, $m and $w:
我有2个数组,$ m和$ w:
$m = Array(
[0] => a
[1] => b
[2] => c
);
$w = Array(
[0] => 1
[1] => 2
[2] => 3
);
How may I combime those 2 arrays to get result like this:
我怎么可以组合这两个数组来获得这样的结果:
$arrFields = Array(
Array(
"VALUE" => a,
"DESCRIPTION" => 1
),
Array(
"VALUE" => b,
"DESCRIPTION" => 2
),
Array(
"VALUE" => c,
"DESCRIPTION" => 3
)
);
Help me to solve this problem, thanks.
帮我解决这个问题,谢谢。
3 个解决方案
#1
3
This code will do the thrick: combine both arrays with the same keys. It also checks if the second array has the same key, otherwise it'll make the description empty.
这段代码可以解决这个问题:将两个数组组合在一起。它还检查第二个数组是否具有相同的键,否则它将使描述为空。
$arrFields = array();
foreach ($m as $k => $v) {
$arrFields[] = array(
'VALUE' => $v,
'DESCRIPTION' => (isset($w[$k]) && !empty($w[$k]) ? $w[$k] : '')
);
}
#2
2
This should work for you:
这应该适合你:
(Here I just go through each element of $m
with array_map()
and return the array with the values from $m
and $w
)
(这里我只使用array_map()遍历$ m的每个元素,并返回数值为$ m和$ w的数组)
<?php
$m = array("a", "b", "c");
$w = array(1, 2, 3);
$arrFields = array_map(function($v)use($w, $m){
return array("VALUE" => $v, "DESCRIPTION" => $w[array_search($v, $m)]);
}, $m);
print_r($arrFields);
?>
Output:
输出:
Array
(
[0] => Array
(
[VALUE] => a
[DESCRIPTION] => 1
)
[1] => Array
(
[VALUE] => b
[DESCRIPTION] => 2
)
[2] => Array
(
[VALUE] => c
[DESCRIPTION] => 3
)
)
#3
2
More convenient way of using array_map function
使用array_map函数更方便的方法
$return = array_map(function($m_item, $w_item){
return array("VALUE" => $m_item, "DESCRIPTION" => $w_item);
}, $m, $w);
print_r($return);
#1
3
This code will do the thrick: combine both arrays with the same keys. It also checks if the second array has the same key, otherwise it'll make the description empty.
这段代码可以解决这个问题:将两个数组组合在一起。它还检查第二个数组是否具有相同的键,否则它将使描述为空。
$arrFields = array();
foreach ($m as $k => $v) {
$arrFields[] = array(
'VALUE' => $v,
'DESCRIPTION' => (isset($w[$k]) && !empty($w[$k]) ? $w[$k] : '')
);
}
#2
2
This should work for you:
这应该适合你:
(Here I just go through each element of $m
with array_map()
and return the array with the values from $m
and $w
)
(这里我只使用array_map()遍历$ m的每个元素,并返回数值为$ m和$ w的数组)
<?php
$m = array("a", "b", "c");
$w = array(1, 2, 3);
$arrFields = array_map(function($v)use($w, $m){
return array("VALUE" => $v, "DESCRIPTION" => $w[array_search($v, $m)]);
}, $m);
print_r($arrFields);
?>
Output:
输出:
Array
(
[0] => Array
(
[VALUE] => a
[DESCRIPTION] => 1
)
[1] => Array
(
[VALUE] => b
[DESCRIPTION] => 2
)
[2] => Array
(
[VALUE] => c
[DESCRIPTION] => 3
)
)
#3
2
More convenient way of using array_map function
使用array_map函数更方便的方法
$return = array_map(function($m_item, $w_item){
return array("VALUE" => $m_item, "DESCRIPTION" => $w_item);
}, $m, $w);
print_r($return);