I have 2 arrays I want to compare and then create a third array with those properties. I have first array (array1) which just includes top of hour time values such as:
Array (
[0] => 1393326000
[1] => 1393329600
[2] => 1393333200
[3] => 1393336800
[4] => 1393340400
[5] => 1393344000
[6] => 1393347600
[7] => 1393351200
[8] => 1393354800
[9] => 1393358400
[10] => 1393362000
[11] => 1393365600
[12] => 1393369200
)
Then I have the second data array that has the data I need, it looks like this, except has thousands of values. (array2)
Array (
[0] => Array ( [time] => 1393328145 [output] => 431 )
[1] => Array ( [time] => 1393328146 [output] => 123 )
[2] => Array ( [time] => 1393354800 [output] => 543 )
)
So I am essentially trying to get a third array that has same keys as array #1, but fill in output
field with what's in array 2, except if it's not in array #2, then just fill it as '0'.
So my final desired result is an array like this:
Array (
[1393326000] => array ( [output] => 0 )
[1393329600] => array ( [output] => 0 )
[1393333200] => array ( [output] => 0 )
[1393336800] => array ( [output] => 0 )
[1393340400] => array ( [output] => 0 )
[1393344000] => array ( [output] => 0 )
[1393347600] => array ( [output] => 0 )
[1393351200] => array ( [output] => 0 )
[1393354800] => array ( [output] => 543 )
[1393358400] => array ( [output] => 0 )
[1393362000] => array ( [output] => 0 )
[1393365600] => array ( [output] => 0 )
[1393369200] => array ( [output] => 0 )
)
Basically all values are 0 except the ones that match from data table, in this case 1393354800
I've tried running a loop on the first array then using this helpful recursive in_array function, but I'm not sure how to get the array values of the same array it finds it in.
// helpful function
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
// do our thing
$newArray = array();
$totalHours = count($array1);
for ($i = 0; $i < $totalHours; $i++)
{
$currentHour = $array1[$i];
if (in_array_r($currentHour, $array2))
{
$newArray[$currentHour] = array('output' => ); // Get output of current array index?
}
else
{
$newArray[$currentHour] = array('output' => '0');
}
}