我有阵列问题,任何人都可以帮助我。 我有阵列A和B的结构:
A:
Array
(
[0] => 2013-08-01
[1] => 2013-08-02
[2] => 2013-08-03
[3] => 2013-08-04
)
和B:
Array
(
[0] => Array
(
[0] => 2013-08-01
[1] => 2
[2] => 0
[3] => 0
)
[1] => Array
(
[0] => 2013-08-02
[1] => 0
[2] => 4
[3] => 0
)
[2] => Array
(
[0] => 2013-08-04
[1] => 0
[2] => 1
[3] => 0
)
)
问题是我想将两个ARRAY(A& B)组合成这样:
Array
(
[0] => Array
(
[0] => 2013-08-01
[1] => 2
[2] => 0
[3] => 0
)
[1] => Array
(
[0] => 2013-08-02
[1] => 0
[2] => 4
[3] => 0
)
[2] => Array
(
[0] => 2013-08-03
[1] => 0
[2] => 0
[3] => 0
)
[3] => Array
(
[0] => 2013-08-04
[1] => 0
[2] => 1
[3] => 0
)
)
任何人都可以帮助我吗?如何合并两个数组..
........
答案 0 :(得分:0)
<?
$a = Array
(
"2013-08-01",
"2013-08-02",
"2013-08-03",
"2013-08-04"
);
$b = Array
(
Array (
"2013-08-01",
2,
0,
0
),
Array (
"2013-08-02",
0,
4,
0
),
Array (
"2013-08-04",
0,
1,
0
)
);
foreach ($a as $a_item) {
$found = FALSE;
foreach ($b as $b_item) {
if($b_item[0]==$a_item) {
$found = TRUE;
}
}
if(!$found) {
$b[] = Array (
$a_item,
0,
0,
0
);
}
}
print_r ($b);
?>
如果阵列中没有大量数据,这应该可以工作。如果您有大量数据,您可能应该重新设计一些以使其更快。
答案 1 :(得分:0)
function combine($a, $b) {
foreach($a as $item_a) {
foreach($b as $item_b) {
if(in_array($item_a, $item_b)) {
continue 2;
}
}
$b[] = array(
$item_a, 0, 0, 0
);
}
usort($b, function($a, $b){return $a[0] > $b[0];});
return $b;
}
答案 2 :(得分:0)
假设核心日期在数组B中,我的方法是循环遍历数组A并在发现日期未在数组B中时添加到数组B.
foreach ($arrA as $datecheck) {
$blnAdd = 1;
foreach ($arrB as $compare) {
if ($compare[0] == $datecheck) {
// If found, don't add!
$blnAdd = 0;
}
}
if ($blnAdd == 1) {
$arrB[] = array($datecheck, 0, 0, 0);
}
}
// When done, sort array B
// Create helper array for multisort
$arrHelper = array();
foreach ($arrB as $data) {
$arrHelper = $data[0];
}
// Then, sort array B using values from helper array
array_multisort($arrHelper, $arrB);
然后,$arrB
应包含您需要的值。