I have multidimensional array where I need to find attribute name “Gallery” and retrieve value for this…in my test this should be “test_gallery”. All with use of PHP. Just a note, order of data in array may change, order of last array will always stay…attribute_id, name, text.
Structure of this array is as per attached image.
PS: here is twig code that does same and works ok:
{% for attribute_group in attribute_groups %} {% for attribute in attribute_group.attribute %} {% if attribute.name == 'Gallery' %} {gallery}{{ attribute.text }}{/gallery} {% endif %} {% endfor %} {% endfor %}
Here is php code I was trying to use:
$arr = $data['attribute_groups']; //my array, print_r values are source of attached image foreach ($arr as $attribute_group){ foreach($attribute_group as $attribute){ print('<pre>'); print_r($attribute); print('</pre>'); if ($attribute['name'] == 'Gallery'){ print('<pre>'); print_r($attribute['text']); print('</pre>'); } } }
Many thanks
Advertisement
Answer
You can retrieve it using nested loops. Depending on the array archistructure, it can be done quite neatly.
I tested it with this code, written based on your attached image:
$attribute_groups = [ 4 => [ 'attribute_group_id' => 4, 'name' => "Multimedia", 'attribute' => [ 0 => [ 'attribute_id' => 26, 'name' => "Gallery", 'text' => "test_gallery", ], 'attribute' => [ 1 => [ 'attribute_id' => 13, 'name' => "Something", 'text' => "test_something", ], ], ] ] ];
I did this to retrieve the group which contains the string that you seek:
$search = "gallery"; foreach ($attribute_groups as $attribute_group) { foreach ($attribute_group['attribute'] as $group) { if (key_exists('name', $group) && strtolower($group['name']) == strtolower($search) ) { print_r($group['text']); } } }
test_gallery