Accessing nested associative array using array_keys (PHP)

匆匆过客 提交于 2019-12-11 15:05:42

问题


I'm trying to access a nested associative array:

$data = array('1'=>'value1','2'=>'value2','3'=>array('one','two'))

The value of the key '3' is an array.

Since I need to cycle my values, I extracted the keys of given array:

$keys = array_keys($data);

and used to get the associated value with:

foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val]; 
 echo "value: ".$data[$keys[$val]]; 
endforeach;

Now I would like to access the values related to '3'. Using $data[$keys[$val]] won't work cause I get back an array, not a value.

My question is: how can I access, for example to the value 'one' using a syntax close to $data[$keys[$val]] ?


回答1:


You should add a condition to check if the value is a string or an array. If it's a string - simply echo it, otherwise - access the first value in that array (key = 0, will print 'one') or use another foreach loop to access all of those array's values.

foreach(range(1, 10) as $val):
 echo "key: ".$keys[$val]; 
 echo "value: ";
 if(is_array($data[$keys[$val]])){ //Is it an array?

  //echo 'one'
  echo $data[$keys[$val]][0];

  //or all the values with a loop
  foreach($data[$keys[$val]] as $val2){
   echo $val2;
   echo ",";
  }


 } else { //it's not an array, we can simply echo it.
  echo $data[$keys[$val]];
 }
endforeach;


来源:https://stackoverflow.com/questions/47309166/accessing-nested-associative-array-using-array-keys-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!