使用array_keys(PHP)访问嵌套的关联数组 [英] Accessing nested associative array using array_keys (PHP)

查看:118
本文介绍了使用array_keys(PHP)访问嵌套的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问嵌套的关联数组:

I'm trying to access a nested associative array:

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

键"3"的值是一个数组.

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;

现在,我想访问与"3"相关的值. 使用$data[$keys[$val]]无效,因为我返回了一个数组,而不是一个值.

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.

我的问题是:如何使用接近$data[$keys[$val]]的语法访问例如值'one'?

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

推荐答案

您应该添加条件以检查该值是字符串还是数组. 如果它是字符串-只需回显它,否则-访问该数组中的第一个值(键= 0,将显示一个"),或使用另一个foreach循环访问这些数组的所有值.

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;

这篇关于使用array_keys(PHP)访问嵌套的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆