Eduardo Rafael
Eduardo Rafael

Reputation: 81

Foreach messes up the values. PHP

I have this function that what it does is add cities.

The code works more or less well but when doing the foreach it messes up the values.

This is the code

    public function updateciudadpreciosdelivery(Request $request)
    {
        $data = $request->except(['_token', 'restaurant_id']);
        $i = 0;
        $str = '{';
        foreach ($data as $day => $times) {
            $str .= '"' . $day . '":[';
            if ($times) {
                foreach ($times as $key => $time) {
                    if ($key % 3 == 0) {
                        $t1 = $time;
                        $str .= '{"open" :' . '"' . $time . '"';
                    }
                    elseif ($key % 2 == 0) {
                        $t3 = $time;
                        $str .= '"cod" :' . '"' . $time . '"}';
                    }
                    else {
                        $t2 = $time;
                        $str .= '"close" :' . '"' . $time . '"';
                    }
                    //check if last, if last then dont add comma,
                    if (count($times) != $key + 1) {
                        $str .= ',';
                    }
                }
                //dd($t3);
            } else {
                $str .= '}]';
            }
            if ($i != count($data) - 1) {
                $str .= '],';
            } else {
                $str .= ']';
            }
            $i++;
        }
        $str .= '}';
        dd($str);
        // Fetches The Restaurant
        $restaurant = Restaurant::where('id', $request->restaurant_id)->first();
        // Enters The Data
        if ($str == "{}") {
                $restaurant->deliveryciudadprecios = null;
        }
        else {
        $restaurant->deliveryciudadprecios = $str;          
        }
        $restaurant->delivery_charge_type = 'XCIUDAD';
        // Saves the Data to Database
        $restaurant->save();
        return redirect()->back()->with(['success' => 'Las ciudades se guardaron correctamente']);      
    }

In the first foreach I get this string with 2 cities added.

1er foreach "{"ciudad":[{"open" :"Piura","close" :"15","cod" :"true"},

2do foreach {"open" :"Lima","cod" :"15"},"close" :"true"]}"

Foreach complete wrong:

{"ciudad":[{"open" :"Piura","close" :"15","cod" :"true"},{"open" :"Lima","cod" :"15"},"close" :"true"]}

As should be the correct foreach

{"ciudad":[{"open" :"Piura","close" :"15","cod" :"true"},{"open" :"Lima","close" :"15","cod" :"true"}]}

As you can see, the order of the cod and close keys changes, why does this happen?

Try to be as clear as possible. If this is poorly written, please just notify us to correct it, please do not report.

My variable $data

array:1 [▼
  "ciudad" => array:6 [▼
    0 => "Piura"
    1 => "10"
    2 => "true"
    3 => "Lima"
    4 => "20"
    5 => "true"
  ]
]

Upvotes: 0

Views: 53

Answers (1)

Barmar
Barmar

Reputation: 781004

Don't create the string using concatenation. Create an array and then convert it to a string with json_encode().

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']);      
}

Upvotes: 1

Related Questions