2
votes

I have the below code in a for..loop is there a way I can add values to the beginning of the array?

    $data = array();

    $initial = strtotime('11:00:00');
    for (; $initial < strtotime("23:00:59");  $initial = strtotime("+15 minutes", $initial)) {
        if ($initial > strtotime("+45 minutes", time())) {
            $row['value'] = date('Hi', $initial);
            $row['label'] = date('H:i', $initial);
            $data['data'][] = $row;
        }
    }

I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.

    if(!isBetween('22:00', '09:59', date('H:i'))) {
        $row['value'] = "asap";
        $row['label'] = "ASAP";
    }

My array output

{
  "data": [
    {
      "value": "1145",
      "label": "11:45"
    }
  ]
}

I want to get this

{
  "data": [
    {
      "value": "asap",
      "label": "ASAP"
    },{
      "value": "1145",
      "label": "11:45"
    },
  ]
}
2
It's not a duplicate.. Tried everything there - moh_abk
Can you post your array structure along with expected output - Narendrasingh Sisodia
"I want to add the below values to the top of the array." - that would take place instead of $data['data'][] = $row;? - VolkerK
I have posted the array @Uchiha - moh_abk

2 Answers

3
votes

Un-shift should work if you pass the arguments correctly:

array_unshift($data["data"], $prepend);

Alternatively, you could use array_merge, like this:

$data["data"] = array_merge(array($prepend), $data["data"]);

With the following example data:

$data = [
    "data" => [
        [
            "value" => "1145",
            "label" => "11:45"
        ]
    ]
];

$prepend = [
    "value" => "asap",
    "label" => "ASAP"
];

$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);

You would get this output (with both solutions):

Array (
    [data] => Array (
            [0] => Array (
                    [value] => asap
                    [label] => ASAP
                )
            [1] => Array (
                    [value] => 1145
                    [label] => 11:45
                )
        )
)
0
votes

If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

function array_unshift_assoc(&$arr, $key, $val) { 
    $arr = array_reverse($arr, true); 
    $arr[$key] = $val; 
    return array_reverse($arr, true); 
} 

Source: http://php.net/manual/en/function.array-unshift.php