cameronmarklewis cameronmarklewis - 7 months ago 64
PHP Question

TWIG, Multidimensional array and Foreach

Using a JSON API feed, I'm getting this using curl and then json_decode which if I'm correct gives me an array. I'm able to display specific data from the array using this

$successes = $data2['Data']['0']['OID'];
.

I'm wanting to extract the OID for each of the data entries on the API, so I end up with a list displaying just all the OID's. My thinking was to use
$first_names = array_column($data2, 'OID');
and then use print_r, but I can't seem to work out how you would then display this correctly using twig?

$url2 = 'https://home-api.letmc.com/v2/tier3/letmcletting/property/properties/'.$letmc_property_id.'/photos?offset=0&count=1000&api_key='.$letmc_apikey.'';
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, $url2);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json'));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
$output2 = curl_exec($ch2);
curl_close($ch2);
$data2 = json_decode($output2, true);

$successes = $data2['Data']['0']['OID'];

$this->_app->render('tennant/tennant-my-property.twig', [
"theOIDs" => $successes,
]);


Example of API feed

{
"Data": [
{
"OID": "0908-703e-0fe1-235c",
"ETag": "0908-703e-0fe1-235c-0",
"Name": "",
"FileName": "white lounge.jpg",
"InspectionItem": "0000-0000-0000-0000",
"InterimInspection": "0000-0000-0000-0000",
"InventoryItem": "0000-0000-0000-0000",
"Property": "0907-f421-2742-7351",
"Room": "0000-0000-0000-0000",
"PhotoNumber": 3
},
{
"OID": "0908-8a9b-c1f9-5219",
"ETag": "0908-8a9b-c1f9-5219-0",
"Name": "",
"FileName": "Large kitchen with island.jpg",
"InspectionItem": "0000-0000-0000-0000",
"InterimInspection": "0000-0000-0000-0000",
"InventoryItem": "0000-0000-0000-0000",
"Property": "0907-f421-2742-7351",
"Room": "0000-0000-0000-0000",
"PhotoNumber": 2
}
],
"Count": 2
}


Any help or ideas would be great!

UPDATE
I'm also able to get a specific entry from the array using twig like this
{{ theOIDs['Data'][0]['OID'] }}
if I change theOIDs to $data2. Is there a way for me to foreach using twig?

Answer

Try this loop:

<ul>
    {% for elem in Data %}
        <li>{{ elem.OID}}</li>
    {% endfor %}
</ul>

A working example in this twigfiddle.

Hope this help