1

How to fetch a multi array branch? For example, I have following array:

$newarr= Array ( 
  "Tommy" => Array ( Array ( "a" => 25, "b" => 304, "c" => 9277 ), 
     Array ( "a" => 25, "b" => 4, "c" => 23 ) 
  ) ,
  "Garry" => Array ( Array ( "a" => 23, "b" => 285, "c" => 8678 ) ,
     Array ( "a" => 23, "b" => 9, "c" => 4 ) 
  )
) ;

How to use foreach to call [Tommy][1] and [Garry][1] only?

I tried the below code.

foreach ($person as $name => $choice?[1]?)
  { 
    foreach ($choice?[1]? as $value)
        { 
           echo "<div class='col-md-6'><br>"; 
           echo $name. "<br>"; 
           echo $value?[1]?["a"]."tries <br>";
           echo $value?[1]?["b"]."times <br>"; 
           echo $value?[1]?["c"]."count <br></div>";
        }
  }

I need output as follows:

Tommy
25
304
9277

Garry
23
285
8678

Thanks

2
  • Provide the code that you tried Commented Oct 14, 2015 at 12:06
  • foreach ($person as $name => $choice?[1]?) { foreach ($choice?[1]? as $value) { echo "<div class='col-md-6'><br>"; echo $name. "<br>"; echo $value?[1]?["a"]."tries <br>"; echo $value?[1]?["b"]."times <br>"; echo $value?[1]?["c"]."count <br></div>";} } Commented Oct 14, 2015 at 12:43

3 Answers 3

1

Simply use foreach like as

$result = [];
foreach($array as $key => $value){
   $result[$key] = $value[1];
}

Edited

$result = [];
foreach($newarr as $key => $value){
   echo "$key<br>";
     foreach($value[1] as $v){
        echo "$v<br>";
     }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please expand on this? What are next steps?
Check this. I think then you can simply use as per your requirement
1

You need to use foreach loop for this.

$required = array();
foreach ($arr as $elem) {
  $required[] = $elem[1];
}

Explanation:

You can use foreach to loop over an array.

You can use either key value pair or just values if needed.

In your case, you need elements from second level sub array.

so, use foreach to get key 1

1 Comment

Could you please review my question, I understood that I can use foreach, not sure how to specify location.
0

Just try with array_map

$result = array_map(function($item) {
  return $item[1];
}, $inputArray);

1 Comment

Ok, which function do I need?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.