Skip to content
Advertisement

Array into array using array_push key issue

I’m getting confused about how to insert array into array and give it a key name. Not number!.

I have the main array, which contains info about customer. the sub array should be called [“verlauf”].

The [“verlauf”] array conatins multiple arrays ( as same as db row count ). the main idea is that the sub array should be having the key name [“verlauf”]. in my code im getting the [0] as key.

Current array output:

array(19) { 
    ["id"]=> string(1) "1" 
    ["name"]=> string(11) "qwert zuiop" 
    ["email"]=> string(23) "xy@gmail.com" 
    ["phn_num"]=> string(12) "123456789" 
    [0]=> array(1) {
        [0]=> array(4) {
            ["datum"]=> string(10) "30.07.2020"
            ["uhr_zeit"]=> string(5) "22:25"
            ["status"]=> string(1) "0"
            ["info"]=> string(34) "some info"
        }
        [1]=> array(4) {
            ["datum"]=> string(10) "30.07.2020"
            ["uhr_zeit"]=> string(5) "23:25"
            ["status"]=> string(1) "1"
            ["info"]=> string(34) "some info"
        }
    }
}

what i want is that the [0] on line 6 in the above example to be ["verlauf"]

My PHP:

while ($row = mysqli_fetch_array($result)) {
     $verlaufArray[] = array(
          "datum"    => $row['datum'],
          "uhr_zeit" => $row['uhr_zeit'],
          "status"   => $row['status'],
          "info"     => $row['info']);
}
array_push($returnArray, $verlaufArray);

Please note that $returnArray is the “main array”.

Advertisement

Answer

You can simply do that by using associate array-

Your PHP code –

while ($row = mysqli_fetch_array($result)) {
     $verlaufArray[] = array(
          "datum"    => $row['datum'],
          "uhr_zeit" => $row['uhr_zeit'],
          "status"   => $row['status'],
          "info"     => $row['info']);
}
$returnArray['verlauf'] = $verlaufArray;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement