GR Vitaly
GR Vitaly

Reputation: 69

Get a specific column value from multi array

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

Upvotes: 1

Views: 85

Answers (3)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

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>";
     }
}

Upvotes: 1

hsz
hsz

Reputation: 152206

Just try with array_map

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

Upvotes: 0

Pupil
Pupil

Reputation: 23948

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

Upvotes: 1

Related Questions