mercredi 6 mars 2019

Loop Multidimensional array in Controller

I need to loop in a mulitidemnsional array being consumed in an outbound API. After consuming the API in a controller, I need to insert the looped records in a Model.

So, the response recieved from the external API is the following:

enter image description here

So, what Im doing in my controller function is the following:

public function index()
{

    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET', 'http://api', [
        'headers' => [
             'x-authtoken' => '0275d',
             'cache-control' => 'no-cache'],
             'decode_content' => false
    ]);

     //get body content
    $body = $response->getBody()->getContents();
    $data = json_decode($body, true);

    foreach ( $data['content']['Propiedades'] as $propiedades )
        {
            $id = Arr::get($propiedades, 'Id');
            $Moneda = Arr::get($propiedades, 'Precio.Moneda');
            $Precio = Arr::get($propiedades, 'Precio.Valor')
        }

}

The problem is that im looping just one instance of "propiedades" array.

enter image description here

1. How can I loop all "propiedades" array and retrieve key values from it?

2. How can access each "propiedades" array to the next nested array and bring back those nested values realted to the first array level? For example, my result must be for each property record:

Propiedades.Id

Propiedades.Precio.Moneda

Propiedades.Precio.Valor

3. Ones I get all the "propiedades" with their values, do I need to create an array to insert those records in a Model? How do I pass the data to the model? My Models will have the structure as the array recevied from the API with the corresponding child entities for "propiedades"


Thanks in advance! Regards



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire