PHP foreach循环键值

我正在运行这个数据库调用让我multidimensional array我试图获得每个的关键,但是当我尝试它出现空白或作为数组。

$root_array = array(); $sites = $this->sites($member_id); foreach ($sites as $site){ $records = $this->db->select('p.name as place_name, p.id as place_id,p.active as place_status') ->from('places p') ->join('members_permissions pm','pm.sites_id = p.sites_id and pm.members_id ='.$member_id) ->where('p.active', 0) ->get(); $places = $records->result_array(); $places['name'] = $site['name']; foreach($places as $place){ $root_array[$site['name']][] = $place; } } return $root_array; 

这里是我的PHP循环:

 <?php foreach($places as $site): ?> <h5><?=key($site)?></h5> <?php foreach($site as $place): ?> <h6><?=$place['place_name']?></h6> <?php endforeach?> <?php endforeach ?> 

另外当我运行一个testing,只是吐出arrays这是结果,我试图呈现的是[费城]

 [Philadelphia] => Array ( [0] => Array ( [place_name] => XYX [place_id] => 103200 [place_status] => 0 ) [1] => Array ( [place_name] => YYYY [place_id] => 232323 [place_status] => 0 ) 

4 Solutions collect form web for “PHP foreach循环键值”

你可以像这样访问你的数组键:

 foreach ($array as $key => $value) 

正如佩卡所述

 foreach ($array as $key => $value) 

你也可能想尝试一个recursion函数

 displayRecursiveResults($site); function displayRecursiveResults($arrayObject) { foreach($arrayObject as $key=>$data) { if(is_array($data)) { displayRecursiveResults($data); } elseif(is_object($data)) { displayRecursiveResults($data); } else { echo "Key: ".$key." Data: ".$data."<br />"; } } } 
 foreach($shipmentarr as $index=>$val){ $additionalService = array(); foreach($additionalService[$index] as $key => $value) { array_push($additionalService,$value); } } 

你也可以使用array_keys() 。 新手友好:

 $keys = array_keys($arrayToWalk); $arraySize = count($arrayToWalk); for($i=0;$i<$arraySize;$i++){ echo "<option value=\"".$keys[$i]."\">".$arrayToWalk[$keys[$i]]."</option>"; } 
  • 在Mac上设置Laravel php artisan迁移错误:没有这样的文件或目录
  • 保存来自PHP URL的图像
  • 在邮件之前如何在PHP中清理用户input?
  • laravel找不到支持的encryption器。 密码和/或密钥长度是无效的
  • 如何用preg_match在数组中search?
  • Symfony2,如何使表单标签类/ attr不同于其input?
  • 获取当前的URL / URI,没有$ _GETvariables
  • 致命错误:调用未定义的函数mb_strlen()