Skip to content
Advertisement

Foreach does not return all values

I have a foreach but it only returns the last value and not all the values, what is the problem?

my array

array:1 [▼
  "ciudad" => array:15 [▼
    0 => "Piura"
    1 => "10"
    2 => "0"
    3 => "Lima"
    4 => "20"
    5 => "0"
    6 => "Pisco"
    7 => "30"
    8 => "0"
    9 => "Arequipa"
    10 => "40"
    11 => "0"
    12 => "Loreto"
    13 => "50"
    14 => "0"
  ]
]

My code:

public function updateciudadpreciosdelivery(Request $request)
{
    $data = $request->except(['_token', 'restaurant_id']);
    $i = 0;
    $result = [];
    foreach ($data as $day => $times) {
        $day_result = [];
        foreach ($times as $key => $time) {
            if ($key % 3 == 0) {
                $day_result["open"] = $time;
            }
            elseif ($key % 2 == 0) {
                $day_result["cod"] = $time;
            }
            else {
                $day_result["close"] = $time;
            }
        }
        $result[$day][] = $day_result;
    }
    // Fetches The Restaurant
    $restaurant = Restaurant::where('id', $request->restaurant_id)->first();
    // Enters The Data
    if (empty($result)) {
        $restaurant->deliveryciudadprecios = null;
    }
    else {
        $restaurant->deliveryciudadprecios = json_encode($result);
    }
    $restaurant->delivery_charge_type = 'XCIUDAD';
    // Saves the Data to Database
    $restaurant->save();
    return redirect()->back()->with(['success' => 'Las ciudades se guardaron correctamente']);      
}

Currently it only returns the last value

"{"ciudad":[{"open":"Loreto","close":"50","cod":"0"}]}"

I need you to return the following (example)

{"ciudad":[{"open" :"Piura","close" :"10","cod" :"0"},{"open" :"Lima","close" :"20","cod" :"0"},{"open" :"Pisco","close" :"30","cod" :"0"},{"open" :"Arequipa","close" :"40","cod" :"0"},{"open" :"Loreto","close" :"50","cod" :"0"}]}

If it is not clear I will try to improve it

Advertisement

Answer

If we consider your data won’t change, and you have 3 entries to get, you can use array_chunk:

$result = [];
foreach ($data as $day => $times) {
    $timesChunked = array_chunk($times, 3);
    
    foreach ($timesChunked as $time) {
        $result[$day] []= [
            'open' => $time[0],
            'close' => $time[1],
            'code' => $time[2],
        ];
    }
}

But your problem was logical, you don’t change the key in your loop, of course your array will have only the last elements. Reread your code, and try to understand why.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement