Can't seem to work out how to access data within an array that has other arrays within it.
My array looks like:
Array
(
[0] => Array
(
[_id] => 28
[serv_image] =>
[serv_name] => My Service
[slug] => my-service
[is_featured] =>
[_blocks] => Array
(
[0] => Array
(
[anchor_heading] => Mats Heading
[_block_type] => anchorHeading
[_block_id] => pe8t69
[_block_index] => 0
)
[1] => Array
(
[anchor_heading] => Another anchored heading
[_block_type] => anchorHeading
[_block_id] => pea49u
[_block_index] => 1
)
)
[_page] => *
[_pageID] => 1
[_sortvalue] => 1003
)
)
So far I've tried this without success:
foreach($services as $service) {
print_r($service['_blocks']['anchor_heading']);
}
This results in undefined index on anchor_heading
.
UPDATE
I will have an unknown amount of these that I need to group together into a variable. How can I ensure I'm grabbing them all, no matter how many other times it's been entered?
You might use 2 times a foreach
and echo the value of anchor_heading:
foreach($services as $service) {
foreach ($service["_blocks"] as $block) {
echo $block["anchor_heading"];
}
}
You have an array for each _block .. so you need an indexed access .. (or an inner iteration)
foreach($services as $service) {
print_r($service['_blocks'][0]['anchor_heading']);
print_r($service['_blocks'][1]['anchor_heading']);
}
(or an inner iteration)
foreach($services as $service) {
$blocks = $service['_blocks'];
foreach( $blocks as $block) {
print_r($block['anchor_heading']);
}
}
You can use the following to access the data within your array in a for loop:
print($service['_blocks'][0]['anchor_heading']);