Reputation: 125
I'm trying to create multidimensional array with start_date
and end_date
values
$array = [];
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
$array[$i]['start_date'] = $row['current_status_start_time'];
$array[$i]['end_date'] = '';
$i++;
}
print_r($array);
This returns me array like this:
Array (
[0] => Array (
[start_date] => 2013-07-25 11:18:42
[end_date] => )
[1] => Array (
[start_date] => 2013-07-26 05:24:08
[end_date] => )
[2] => Array (
[start_date] => 2013-07-31 17:25:05
[end_date] => )
)
end_date
should get next array [start_date]
node value:
Array (
[0] => Array (
[start_date] => 2013-07-25 11:18:42
[end_date] => **2013-07-26 05:24:08**)
[1] => Array (
[start_date] => **2013-07-26 05:24:08**
[end_date] => 2013-07-31 17:25:05)
[2] => Array (
[start_date] => 2013-07-31 17:25:05
[end_date] => current_date)
)
As you can see in the last code example, array[0][end_date]
should get array[1][start_date]
value and so on, the last array end_date
should get current time value, because there is end of array.
Should I use second loop to achieve that? or there is alternative and more simple way?
Upvotes: 0
Views: 175
Reputation: 3053
I would go with a loop. Something like this:
foreach($mainArray as $key => $value)
{
$next = $key + 1;
if(!is_null($mainArray[$next]['start_date']))
{
$mainArray[$key]['end_date'] = $mainArray[$next]['start_date'];
}
else
{
$mainArray[$key]['end_date'] = current_date;
}
}
print_r($main_array);
Upvotes: 1
Reputation: 24645
This should get you what you want:
$array = [];
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
$array[$i]['start_date'] = $row['current_status_start_time'];
$array[$i]['end_date'] = '';
if ($i > 0){
// if we are pass the first item set the previous item to the current start date
$array[$i-1]["end_date"] = $array[$i]['start_date'];
}
$i++;
}
// fill in the last end_date with the current_date
$array[$i]["end_date"] = date("Y-m-d H:i:s");
print_r($array);
Upvotes: 2