使用php组合单维和多维数组

时间:2014-10-08 14:37:23

标签: php arrays

我有两个数组,我想匹配两个数组。如果array 1中没有array 2的值,那么我想为该元素添加0

阵列1

$weeksArr = array("p1","p2","p3","p4");

数组2

$dailyArr = array(
    "0"=>array("p1","123"),
    "1"=>array("p2","125"),
    "2"=>array("p4","126")
);

加入后我希望最终的数组是

$finalArr = array(
    "0"=>array("p1","123"),
    "1"=>array("p2","125"),
    "2"=>array("p3","0"),
    "3"=>array("p4","126")
);

所以我想在最终数组中插入p3

非常欢迎任何提示/建议。提前谢谢。

3 个答案:

答案 0 :(得分:3)

我不知道到达那里的最短途径,但你可以先得到所有的p,然后比较周。

获得差异后,循环分配,然后再次对它们进行排序。

$weeksArr = array("p1","p2","p3","p4");
$dailyArr = array("0"=>array("p1","123"),"1"=>array("p2","125"),"2"=>array("p4","126"));
$finalArr = $dailyArr;

$temp = array_map(function($piece){ return $piece[0]; }, $finalArr); // get all p's
$diff = array_diff($weeksArr, $temp); // get the missing p
foreach($diff as $w) { 
    $finalArr[] = array($w, 0); // assign missing p
}
usort($finalArr, function($a, $b){ // you do not need this is you do not care about the order
    return strcmp($a[0], $b[0]); // if you need to order them, p1, p2, p3, p4, then i guess you need to sort
});

echo '<pre>';
print_r($finalArr);

答案 1 :(得分:2)

比我想的有点棘手,但这个简单的嵌套foreach循环将使它成为:

$weeksArr = array("p1","p2","p3","p4");
$dailyArr = array("0"=>array("p1","123"),"1"=>array("p2","125"),"2"=>array("p4","126"));

foreach ($weeksArr as $i => $value) {
  foreach ($dailyArr as $a) {
    if ($a[0] == $value) $finalArray[$i] = array($a[0],$a[1]);
  }
  if (!isset($finalArray[$i])) $finalArray[$i] = array($value,0);
}

var_dump($finalArray);

答案 2 :(得分:0)

  1. 排序$ weeksArr

  2. 按$ dailyArr排序$ dailyArr [i] [0]&lt; = $ dailyArr [i + 1] [0]

  3. 初始化两个变量i,j为0,$ finalArray为空数组

  4. DO

    4.a如果$ weeksArr [i]等于$ dailyArr [j] [0],将$ dailyArr [j]添加到$ finalArr并增加i和j

    4.b if $ weeksArr [i]&lt; $ dailyArr [j] [0],为$ weekArr [i]添加$ finalArr的新条目并增加i

    1. 取消循环,如果i或j超出范围
    2. LOOP

      1. 如果我小于$ weekArr的长度,则将剩余的条目添加到$ finalArr