在php中获取所有未匹配到数组中的数据库的值

时间:2017-10-10 10:05:10

标签: php mysql

我有一个像这样的日期数组

Array (
[0] => 07/2016
[1] => 08/2016
[2] => 09/2016
[3] => 10/2016
[4] => 11/2016
[5] => 12/2016
[6] => 01/2017
[7] => 02/2017
[8] => 03/2017
[9] => 04/2017
[10] => 05/2017
[11] => 06/2017
[12] => 07/2017
[13] => 08/2017
[14] => 09/2017
[15] => 10/2017
)

然后我将像这样做#fore循环

foreach($getDate as $mydate)
            {
                $db = JFactory::getDbo();
                $getdata_sql = " select DATE_FORMAT(completed_date, '%m/%Y') as date,SUM(total_amount) as amount from #__scheduled_orders where userid='".$cuid."'  GROUP BY date ORDER BY completed_date";
                $db->setQuery($getdata_sql);
                $result = $db->loadObjectList();    
                $myarray = $result;
            }
            $array=array();
            foreach($myarray as $row)
            {
                $array2=array();
                $getFinalData = array();
                $array2[0]=$row->date;
                $array2[1]=floatval(number_format($row->amount, 2, '.', ''));
                $array[]=$array2;    
            }

我会像这样离开

Array (

[0] => Array (
        [0] => 07/2016
        [1] => 124.19
    )

[1] => Array
    (
        [0] => 10/2016
        [1] => 248.38
    )

[2] => Array
    (
        [0] => 12/2016
        [1] => 124.19
    )

[3] => Array
    (
        [0] => 01/2017
        [1] => 248.38
    )

[4] => Array
    (
        [0] => 09/2017
        [1] => 124.19
    )

[5] => Array
    (
        [0] => 10/2017
        [1] => 124.19
    )

)

但我会得到像这样的输出

Array (
[0] => Array
    (
        [0] => 07/2016
        [1] => 124.19
    )
[1] => Array
    (
        [0] => 08/2016
        [1] => 0
    )
[2] => Array
    (
        [0] => 09/2016
        [1] => 0
    )
[3] => Array
    (
        [0] => 10/2016
        [1] => 248.38
    )
[4] => Array
    (
        [0] => 11/2016
        [1] => 0
    )
[5] => Array
    (
        [0] => 12/2016
        [1] => 0
    )
[6] => Array
    (
        [0] => 1/2017
        [1] => 0
    )
[7] => Array
    (
        [0] => 2/2017
        [1] => 0
    )
[8] => Array
    (
        [0] => 3/2017
        [1] => 0
    )
[9] => Array
    (
        [0] => 4/2017
        [1] => 0
    )
[10] => Array
    (
        [0] => 5/2017
        [1] => 0
    )
[11] => Array
    (
        [0] => 6/2017
        [1] => 0
    )
[12] => Array
    (
        [0] => 7/2017
        [1] => 0
    )
[13] => Array
    (
        [0] => 8/2017
        [1] => 0
    )
[14] => Array
    (
        [0] => 9/2017
        [1] => 0
    )
[15] => Array
    (
        [0] => 10/2017
        [1] => 0
    )
)

我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用array key将带有空值的日期添加到您的foreach中,以便您可以调用索引及其值,例如:

$array = [
  '201607'=>['07/2016',0], 
  '201608'=>['08/2016',0], 
  '201609'=>['09/2016',0]
];

现在,您可以使用数据库值轻松更改值,如:

$array['201608'][1] = 124.19;

所有未填充的值将保持为0
阵列将成为:

$array = [
  '201607'=>['07/2016',0], 
  '201608'=>['08/2016',124.19], 
  '201609'=>['09/2016',0]
];