Reputation: 1251
I need to go beyond the results of this [question]: Comparing database result and multidimensionnal array
I need to add values to the array.
I look for the key (ie: "2017-03-30"). If key exists, I need to add an hour to the existing array value, associated to the related key/date. To make myself as clear as possible : I have a date + hour such as '2017-03-30' + '11:00'.
I use array key exists and if result is true, I need to push the hour into the sub-array.
'2017-03-30' => array('9:00','10:00','14:00')
//needs to become
'2017-03-30' => array('9:00','10:00','14:00','11:00')
//or
'2017-03-30' => array('9:00','10:00','11:00','14:00')
if result is false, I need to add the date+hour into the array.
array( '2017-03-24' => array('14:00'), '2017-03-29' => array('15:00') )
//will become :
array( '2017-03-24' => array('14:00'), '2017-03-29' => array('15:00'), '2017-03-30' => array('11:00') )
I searched for a function, but neither array_push nor array_merge will do the job. Is there a way to achieve this?
Upvotes: 1
Views: 68
Reputation: 146
I would use a generic function like this, which sadly I don't think exists in PHP's general functions
function array_push_sub(&$table, $key, $value) {
if(array_key_exists($key, $table)) $table[$key][] = $value;
else $table[$key] = [$value];
}
$myArray = [];
array_push_sub($myArray, "2017-03-21", "09:00");
//Please note that $table[$date][] = $time;
//Is the same as array_push($table[$date], $time);
Upvotes: 1
Reputation: 626
Just use $arrayVariable['wantedKey'] = $insertedArray
, like
$startArray = array( '2017-03-24' => array('14:00'), '2017-03-29' => array('15:00') );
$startArray['2017-03-30'] = array('11:00');
And that will get You your wanted array.
Upvotes: 0