0

i have been trying to solve this but i could not do it by myself

So i have this sql query:

SELECT * FROM stats WHERE date >= '2014-03-01' and date <= '2014-03-07'

+-----------------------------+
+ date        | visits        +
+-----------------------------+
+  2014-03-02 | 832           +
+  2014-03-03 | 746           +
+  2014-03-06 | 49            +                 
+-----------------------------+

I want to combine it with a php array so i get this output:

$array = array(
    "2014-03-01" => 0,
    "2014-03-02" => 832,
    "2014-03-03" => 746,
    "2014-03-04" => 0,
    "2014-03-05" => 0,
    "2014-03-06" => 49,
    "2014-03-07" => 0,
);

Does anyone know how to get this done? Thank you very much for helping

1
  • Is $array already defined (with keys), or are you building it dynamically when you get your db values? Commented Apr 14, 2014 at 3:31

2 Answers 2

2

First crate an array with :

$array1 = array(
    "2014-03-01" => 0,
    "2014-03-02" => 0,
    "2014-03-03" => 0,
    "2014-03-04" => 0,
    "2014-03-05" => 0,
    "2014-03-06" => 0,
    "2014-03-07" => 0,
);

Then get the array from db with:

$array2 = array(
    "2014-03-02" => 832,
    "2014-03-03" => 746,
    "2014-03-06" => 49,
);

Last get the result with:

$result = array_merge($array1, $array2);
Sign up to request clarification or add additional context in comments.

Comments

1

(I know it's already answered)
The hard part (for me) was getting (@xdazz's) array1.
I found it at http://www.rarst.net/script/php-date-range/

$datearray1 = dateRange('2014/03/01', '2014/03/07');
$datearray1 = array_fill_keys($datearray1, 0);
$datearray2 = array('2014-03-02' => 832, '2014-03-03' => 746, '2014-03-06' => 49);
$datearray3 = array_replace($datearray1, $datearray2);
// http://www.rarst.net/script/php-date-range/
function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
    $dates = array();
    $current = strtotime( $first );
    $last = strtotime( $last );
    while( $current <= $last ) {
        $dates[] = date( $format, $current );
        $current = strtotime( $step, $current ); }
    return $dates;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.