The following are four available options:
<?php $arr = ["2" => [ ["first_name"=> "khalfan", "last_name"=> "mussa", "date"=>"2017-06-06 09:21:36", "gender"=> "male"], ["services" => ["8" => ["name" => "See a Doctor","results"=> ""], "9" => ["name"=> "Kichocho","results"=> "FD- 73"] ] ] ]]; for ($i=0, $max=count($arr["2"]); $i < $max; $i++) { if ( isset( $arr["2"][$i]["services"])) { $a = $arr["2"][$i]["services"]; foreach($a as $e) { echo $e["name"],"\t"; echo $e["results"],"\n"; } } continue; }
See live code
The advantage here is that the code does work with a foreach as per the OP's request. But the code is involved and not as fast as it could be, owing to that if conditional.
Another solution that is faster:
<?php $arr = ["2" => [ ["first_name"=> "khalfan", "last_name"=> "mussa", "date"=>"2017-06-06 09:21:36", "gender"=> "male"], ["services" => ["8" => ["name" => "See a Doctor","results"=> ""], "9" => ["name"=> "Kichocho","results"=> "FD- 73"] ] ] ]]; $count = count($arr["2"]); $last = $count - 1; // b/c of zero-based indexing foreach ($arr as $e) { foreach($e[$last]["services"] as $a) { echo $a["name"],"\t"; echo $a["results"],"\n"; } } // Or an easier solution without resorting to foreach: array_walk_recursive($arr,function($item,$key) { if ($key == "name") echo $item,"\t"; if ($key == "results") echo $item,"\n"; });
See live code
Whether $arr["2"] contains two elements or more as long as the last one is the "services" associate array, this foreach code works. But, this type of "array walk" can best be carried out with a built-in function designed for this very purpose, array_walk_recursive. With this function, you don't have to worry about how to construct the perfect foreach; the iteration occurs behind the scenes and all you need is to supply a callback. array_walk_recursive will drill down to the "services" element and if there is one or more associative arrays with keys of "name" and "results", then their respective values display.
The fourth possibility is one of those "why would you" situations. Why take an array and json_encode it and then json_decode it back to an array and then apply array_walk_recursive? But, the code does work:
<?php $arr = ["2" => [ ["first_name"=> "khalfan", "last_name"=> "mussa", "date"=>"2017-06-06 09:21:36", "gender"=> "male"], ["services" => ["8" => ["name" => "See a Doctor","results"=> ""], "9" => ["name"=> "Kichocho","results"=> "FD- 73"] ] ] ]]; $result=json_decode(json_encode($arr),true); array_walk_recursive($result, function($value,$key){ if ($key == "name" ) { echo $value,"\t";} if ($key == "results") { echo $value,"\n";} });
See live code
foreach.foreachgives you the index.foreach(). what's the issue there? what is not working or what issue you are facing?$service[8]['name'], do you mind the index8there. What if I don't know the Index8@Alive to Die