Skip to content
Advertisement

Include variable into array if not empty inside foreach

Include the name variable if the value is not empty inside the foreach. I tried this method code below but it include outside the array. I want to include within the array.

Sample Code:

$load_array = array();
foreach($stmt->fetchAll() as $row){

    $load_array[] = array(
      'name' => $row['name'],
      'start_location' => array(
        'address' => $row['start_address'],
        'coords'  => array (
          'lat'   => floatval($row['start_lat']),
          'lng'   => floatval($row['start_lng']),
        ),
      ),
    );

    if(!empty($row['shift_start'])) {     $load_array['shift_start']   = $row['shift_start'];}
    if(!empty($row['shift_end'])) {       $load_array['shift_end']     = $row['shift_end'];}
}
return json_encode($load_array);

Output code above:

{
   "0": {
   "name": "Ramon Macger",
   "start_location": {
   "address": "76 Spilman Street GORSGOCH SA40 8ZB",
   "coords": {
    "lat": 42.45188,
    "lng": -83.12829
     }
    }
   },
    "1": {
    "name": "Roberto",
    "start_location": {
    "address": "76 Spilman Street GORSGOCH SA40 8ZB",
    "coords": {
      "lat": 42.45188,
      "lng": -83.12829
    }
   }
 },
 "shift_start": "14:00",
 "shift_end": "17:00"

}

The output should be like this:

    {
   "0": {
   "name": "Ramon Macger",
   "start_location": {
      "address": "76 Spilman Street GORSGOCH SA40 8ZB",
      "coords": {
        "lat": 42.45188,
        "lng": -83.12829
       }
    },
    "shift_start": "14:00",
    "shift_end": "17:00"
    
   },
    "1": {
    "name": "Roberto",
    "start_location": {
       "address": "76 Spilman Street GORSGOCH SA40 8ZB",
       "coords": {
         "lat": 42.45188,
         "lng": -83.12829
       }
     },
     "shift_start": "14:00",
     "shift_end": "17:00"
   },

 
}

The shift_start and shift_end should be within the array not outside. My code is working in 1 array only and not on the foreach. However, it doesn’t working within for each.

Advertisement

Answer

You need to add shift_start and shift_end values into the data array before you push it into $load_array. Something like this:

foreach($stmt->fetchAll() as $row){
    $data = array(
      'name' => $row['name'],
      'start_location' => array(
        'address' => $row['start_address'],
        'coords'  => array (
          'lat'   => floatval($row['start_lat']),
          'lng'   => floatval($row['start_lng']),
        ),
      ),
    );
    if(!empty($row['shift_start'])) {
        $data['shift_start']   = $row['shift_start'];
    }
    if(!empty($row['shift_end'])) { 
        $data['shift_end']     = $row['shift_end'];
    }
    $load_array[] = $data;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement