比较循环中的数组并获取当前数组索引

时间:2022-09-26 23:30:54

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:

我有2个我想比较的数组,然后用这些属性创建第三个数组。我有第一个数组(array1),它只包括小时时间值的顶部,例如:

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)

然后我有第二个数据数组,它有我需要的数据,它看起来像这样,除了有数千个值。 (数组2)

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'.

所以我基本上试图获得第三个与数组#1具有相同键的数组,但是用数组2中的内容填充输出字段,除非它不在数组#2中,然后将其填充为“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

基本上所有值都是0,除了与数据表匹配的值,在本例中为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.

我已经尝试在第一个数组上运行循环,然后使用这个有用的递归in_array函数,但我不知道如何获取它找到的相同数组的数组值。

// 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');
    }
}

5 个解决方案

#1


1  

This should do the job (without your helpful function):

这应该做的工作(没有你的有用功能):

$newArray = array();
foreach ($array1 as $hour) {
    // you need to go through the whole array anyway
    foreach ($array2 as $k => $o) {
        if ($o["time"] != $hour) continue;

        // only reached if the hour matches -> add entry to $newArray
        $newArray[$hour] = array("output" => $o["output"]);

        // remove from array2 to speed up things a little:
        // it has already been found, we don't need to compare this upon the next iteration
        unset($array2[$k]);

        // this basically goes back to the top of the outer loop
        continue 2;
    }
    // this is only reached when the $array2 loop never found anything
    // so add the 0 value to the array
    $newArray[$hour] = array("output" => 0);
}

#2


3  

// "time" column, same as array_column($array2, 'time') in PHP 5.5+
$times = array_map('reset', $array2);

// "output" column
$out   = array_map('end', $array2);

// combine columns, and merge them with missing keys
$final = array_combine($times, $out) + array_fill_keys(array_values($array1), 0);

You might need to sort the final array by time (ksort)

您可能需要按时间对最终数组进行排序(ksort)

#3


1  

Here's a straightforward way to do it. I edited your helper function slightly, so that if it finds the needle in the haystack, it returns that item.

这是一种直截了当的方式。我稍微编辑了你的辅助函数,这样如果它在大海捞针中找到了针,它会返回该项。

// helpful function, edited slightly
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 $item;
        }
    }
    return false;
}

$newArray = array();
$totalHours = count($array1);

foreach ($array1 as $key => $value) {
    $result = in_array_r($value, $array2);
    if($result != FALSE) {
        $newArray[$value] = $result['output'];
    }
}

#4


1  

Here's a way to do it by first building array3 with the default value, then looping over array2 and adding the matching values

这是一种方法,首先使用默认值构建array3,然后在array2上循环并添加匹配值

$emptyValues = array_fill(0, count($array1), array('output' => 0));
$array3 = array_combine(array_flip($array1), $emptyValues);

foreach ($array2 as $value) {
    if (isset($array3[$value['time']])) {
        $array3[$value['time']]['output'] = $value['output'];
    }
}

#5


1  

Give this a try:

尝试一下:

$array_1 = ...; // your first array
$array_2 = ...; // your second array

// get Array #2 into a workable format
// build a map/array with `time` values as keys and `output` values as values
$time_to_output_map = array();
array_walk($array_2, function ($value, $key_not_used) use ($time_to_output_map) {
    $time_to_output_map[$value['time']] = $value['output'];
});

// get the values in array 1 set up as keys
$array_1_flipped = array_flip($array_1);

// merge arrays on keys
$final_array = array();
foreach($array_1_flipper as $key => $value_not_used) {
    if (array_key_exists($key, $time_to_output_map)) {
        $final_array[$key] = $time_to_output_map['$key'];
    } else {
        $final_array[$key] = 0;
    }
}

#1


1  

This should do the job (without your helpful function):

这应该做的工作(没有你的有用功能):

$newArray = array();
foreach ($array1 as $hour) {
    // you need to go through the whole array anyway
    foreach ($array2 as $k => $o) {
        if ($o["time"] != $hour) continue;

        // only reached if the hour matches -> add entry to $newArray
        $newArray[$hour] = array("output" => $o["output"]);

        // remove from array2 to speed up things a little:
        // it has already been found, we don't need to compare this upon the next iteration
        unset($array2[$k]);

        // this basically goes back to the top of the outer loop
        continue 2;
    }
    // this is only reached when the $array2 loop never found anything
    // so add the 0 value to the array
    $newArray[$hour] = array("output" => 0);
}

#2


3  

// "time" column, same as array_column($array2, 'time') in PHP 5.5+
$times = array_map('reset', $array2);

// "output" column
$out   = array_map('end', $array2);

// combine columns, and merge them with missing keys
$final = array_combine($times, $out) + array_fill_keys(array_values($array1), 0);

You might need to sort the final array by time (ksort)

您可能需要按时间对最终数组进行排序(ksort)

#3


1  

Here's a straightforward way to do it. I edited your helper function slightly, so that if it finds the needle in the haystack, it returns that item.

这是一种直截了当的方式。我稍微编辑了你的辅助函数,这样如果它在大海捞针中找到了针,它会返回该项。

// helpful function, edited slightly
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 $item;
        }
    }
    return false;
}

$newArray = array();
$totalHours = count($array1);

foreach ($array1 as $key => $value) {
    $result = in_array_r($value, $array2);
    if($result != FALSE) {
        $newArray[$value] = $result['output'];
    }
}

#4


1  

Here's a way to do it by first building array3 with the default value, then looping over array2 and adding the matching values

这是一种方法,首先使用默认值构建array3,然后在array2上循环并添加匹配值

$emptyValues = array_fill(0, count($array1), array('output' => 0));
$array3 = array_combine(array_flip($array1), $emptyValues);

foreach ($array2 as $value) {
    if (isset($array3[$value['time']])) {
        $array3[$value['time']]['output'] = $value['output'];
    }
}

#5


1  

Give this a try:

尝试一下:

$array_1 = ...; // your first array
$array_2 = ...; // your second array

// get Array #2 into a workable format
// build a map/array with `time` values as keys and `output` values as values
$time_to_output_map = array();
array_walk($array_2, function ($value, $key_not_used) use ($time_to_output_map) {
    $time_to_output_map[$value['time']] = $value['output'];
});

// get the values in array 1 set up as keys
$array_1_flipped = array_flip($array_1);

// merge arrays on keys
$final_array = array();
foreach($array_1_flipper as $key => $value_not_used) {
    if (array_key_exists($key, $time_to_output_map)) {
        $final_array[$key] = $time_to_output_map['$key'];
    } else {
        $final_array[$key] = 0;
    }
}