Raj
Raj

Reputation: 1437

Combine single and multidimensional array using php

I have 2 arrays and I want to match both arrays.If the value from array 1 is not present in array 2 then I would like to put 0 for that element.

Array 1

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

Array 2

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

After joining I would like to the final array to be

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

So I would like to insert p3 inside final array.

Any hint/suggestion is highly welcomed. Thanks in advance.

Upvotes: 0

Views: 46

Answers (3)

Was a bit trickier then I thought, but this simple nested foreach loop will make it:

$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);

Upvotes: 2

Kevin
Kevin

Reputation: 41885

I do not know the shortest way to get there, but you could get all the p's first then compare to the weeks.

After getting the differences, loop that an assign, then finally sort them again.

$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);

Upvotes: 3

UniversE
UniversE

Reputation: 2507

  1. sort $weeksArr

  2. sort $dailyArr such that $dailyArr[i][0] <= $dailyArr[i+1][0]

  3. initialize two variables i,j with 0 and $finalArray with an empty array

DO

4.a if $weeksArr[i] equals $dailyArr[j][0], add $dailyArr[j] to $finalArr and increment i and j

4.b if $weeksArr[i] < $dailyArr[j][0], add a new entry to $finalArr for $weekArr[i] and increment i

  1. cancel loop if i or j gets out of bounds

LOOP

  1. if i is smaller than the length of $weekArr, then add the remaining entries to $finalArr

Upvotes: 0

Related Questions