jagcweb
jagcweb

Reputation: 350

How to output three arrays stored in one?

I am saving this array in my database:

$voz = array(); $datos = array(); $posicion_movil = array();

for ($i = 0; $i <= (int)$total_data["general_total_movil"]-1; $i++) {
   array_push($posicion_movil, $i);
   array_push($voz, "ilimitado");
   array_push($datos, $data["movil_datos_datos-nacional"][$i]);

}

$movil = array(
   "posicion" => $posicion_movil,
   "voz" => $voz,
   "datos" => $datos
);

$mi_resumen =  new MyTariffResume();
$mi_resumen->movil = json_encode($movil, JSON_FORCE_OBJECT);
$mi_resumen->save();

Im decoding this json:

$mi_tarifa = MyTariffResume::where('user_id', \Auth::user()->id)->first();
$movil = json_decode($mi_tarifa["movil"], true);

But when I decide to loop through the array in my laravel blade ...

@foreach($movil as $i=>$movi)
{{$movi[$i]}} //Undefined index: posicion
 @endforeach

@foreach($movil as $i=>$movi)
   {{$movi[0]}} //a full iteration (0, "ilimitado", 20)
@endforeach

@foreach($movil as $i=>$movi)
   {{$movi[0][$i]}} //Illegal string offset 'voz' 
@endforeach

@foreach($movil as $i=>$movi)
   {{$movi[$i][0]}} //Undefined index: posicion
@endforeach

@foreach($movil as $i=>$movi)
    {{$movi[0][0]}} //Undefined index: posicion
@endforeach

How can i fix this? I have nothing left to prove and I don't know what else to do.

JSON example that I am saving to my database:

{"posicion":{"0":0,"1":1},"voz":{"0":"ilimitado","1":"ilimitado"},"datos":{"0":"ilimitado","1":"60_gb_100_gb"}}

Upvotes: -1

Views: 86

Answers (3)

mrhn
mrhn

Reputation: 18926

Your code is very complex for what you are trying to do. But to make your code work, you are misunderstanding what foreach does on objects.

Imagine the following data.

{"posicion":{"0":0,"1":1}}

The following foreach call.

@foreach($movil as $i=>$movi)

Will only run 1 time, then $i will be 'posicion' and $movi be {"0":0,"1":1}. You are accessing the key posicion on $movi. Changing your code to this should make it work. Then do it accordingly across the code.

@foreach($movil as $i=>$movi)
    {{$movil[$i][0]}}
@endforeach

Upvotes: 0

jagcweb
jagcweb

Reputation: 350

I have solved it much easier than I thought...

    $movil = json_decode($mi_tarifa->movil, true);
    $total_moviles = count($movil["voz"]);

@for ($i = 0; $i <= $total_moviles-1; $i++)
     <p><strong>Móvil {{$i+1}}</strong></p>
     <p><strong>Voz</strong>: {{$movil["voz"][$i]}}</p>
     <p><strong>Datos</strong>: {{$movil["datos"][$i]}}</p>
@endfor

Thank you all for your time.

Upvotes: 1

Med.ZAIRI
Med.ZAIRI

Reputation: 190

You should loop on all items in your array:

@foreach($movil as $i=>$movi)
   @foreach($movi as $key => $item)
    {{ $i.' '.$key.' - '.$item }}
   @endforeach
@endforeach

Upvotes: 0

Related Questions