James James - 3 months ago 10
PHP Question

Accessing in arrays using twig templating engine

Little stuck with something.... I am able to grab {{ value.title }} which displays fine however getting the inner array value it is not showing and not sure what im doing wrong here... never used twig before so might be just me missing something.

PHP

$product_array = array();

foreach ($shopifyProducts as $product) {
$item = array(
"title" => $product["title"], // product title
"variants" => array() // for now an empty array, we will fill it in the next step
);
foreach($product["variants"] as $variant) {
$item["variants"][] = array(
"barcode" => $variant["barcode"], // product barcode
"sku" => $variant["sku"] // product SKU
);
}
$product_array[] = $item; // now we add the item with all the variants to the array with all the products
}


TWIG

<div class="table-responsive">
<table class="table">
<thead>
<th>Title</th>
<th>Barcode</th>
<th>SKU</th>
</thead>
<tbody>
<tr ng-repeat="value in remote_data">
<td>{{ value.title }}</td>
<td>{{ value.variants.barcode }}</td>
<td>{{ value.variants.sku }}</td>
<td>{{ value.variants }}</td>
</tr>
</tbody>
</table>
</div>


If i output vaule.variants it outputs

[{"barcode":"5060315468600","sku":"PLU#1"}]


But cant seem to get the barcode and sku to display any ideas?

Answer

The variants attribute is an array, you should cycle in it, as example:

{% for variant in value.variants %}

<td>{{ value.title }}</td>
<td>{{ variant.barcode }}</td>
<td>{{ variant.sku }}</td>

{% endfor %} 

Here a working example with the sample data provided.

Probably, seen your code, is better you change the structure of your data (you need to display always the product's title) and simplify the twig code, as example I propose you the following:

PHP

$product_array = array();

foreach ($shopifyProducts as $product) {

    foreach($product["variants"] as $variant) {
        $product_array[] = array(
            'title' => $product["title"], // always display the product title
            "barcode" => $variant["barcode"], // product barcode
            "sku" => $variant["sku"] // product SKU
        );
    }// end foreach
}// end foreach

TWIG

<div class="table-responsive">
    <table class="table">
      <thead>
        <th>Title</th>
        <th>Barcode</th>
        <th>SKU</th>
      </thead>
      <tbody>
        <tr ng-repeat="value in remote_data">
          <td>{{ value.title }}</td>
          <td>{{ value.barcode }}</td>
          <td>{{ value.sku }}</td>
        </tr>
      </tbody>
   </table>
</div>
Comments