1

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.

1 Answer 1

1

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.