从2个现有数组创建新数组

时间:2016-03-15 07:07:08

标签: php arrays

我有一个初始的日期数组:

Array ( [0] => 2015-11-23 [1] => 2015-11-24 [2] => 2015-11-25 [3] => 2015-11-26 [4] => 2015-11-27 [5] => 2015-11-28 [6] => 2015-11-29 ) 

和另一个“结果”数组:

Array ( 
   [0] => stdClass Object ( [order_date] => 2015-11-24 [SUM(order_total)] => 1458.5 ) 
   [1] => stdClass Object ( [order_date] => 2015-11-25 [SUM(order_total)] => 1540 ) 
   [2] => stdClass Object ( [order_date] => 2015-11-26 [SUM(order_total)] => 1256 ) 
   [3] => stdClass Object ( [order_date] => 2015-11-27 [SUM(order_total)] => 2516.5 ) 
   [4] => stdClass Object ( [order_date] => 2015-11-28 [SUM(order_total)] => 3436.5 ) )

如何创建一个新数组,该数组返回初始数组中的日期及结果数组中的相应值(如果存在),但如果不返回0?

到目前为止,如果$ dates是日期数组而$ day_of_week_array是结果数组,我试过这个:

foreach ($dates as $date) {
    echo $date."<br>";
        foreach($day_of_week_array as $day_data){
            $day_date = 'order_date';
            $total = 'SUM(order_total)';
            if ($date === $day_of_week_array->$day_date) {
            echo $day_data->$total."<br>";
        }
else { }
}
}

然而,这似乎相当复杂,并且如果日期不匹配(因为数组是嵌套的),则不允许我返回0,因此无法实现练习的目的。

3 个答案:

答案 0 :(得分:1)

尝试 -

$new= array();
foreach($day_of_week_array as $day_data) {
    // Check if the date exists
    if (in_array($day_data->order_date, $dates, true)) {
        $new[$day_data->order_date]= array('Date' => $day_data->order_date, 
                                           'Total' => $day_data->{'SUM(order_total)'});
    }
}
$missed= array_diff($dates, array_keys($new)); // Empty dates
foreach($missed as $d) {
    $new[$d]= array('Date' => $d, 
                    'Total' => 0);
}

Demo

答案 1 :(得分:1)

请考虑以下代码:

$result_array = array();
foreach ($dates as $date) {
    $found_flag = 0;
    echo $date."<br>";
    foreach($day_of_week_array as $day_data){
        $day_date = 'order_date';
        $total = 'SUM(order_total)';
        if ($date === $day_of_week_array->$day_date) {
            // echo $day_data->$total."<br>";
            $temp_array = array(
                    'date' => $date,
                    'sum' => $day_data->$total
                );
            array_push($result_array, $temp_array);
            $found_flag = 1;
        }
    }
    if(!$found_flag){
        $temp_array = array(
                'date' => $date,
                'sum' => 0
            );
        array_push($result_array, $temp_array);
    }
}

print_r($result_array); //Your ouptut

答案 2 :(得分:0)

试试这段代码:)

foreach($results as $result){
  if(key_exists($result->order_date, $dates)){
    $dates[$result->order_date] = $result->{'SUM(order_total)'};
  }
}

这里有$dates数组,其中包含来自结果数组的值,用于相应的order_date。