PHP foreach循环键值

时间:2009-12-02 18:00:25

标签: php foreach

我正在运行此DB调用以获取多维数组 我试图得到每个键,但当我尝试它出现空白或作为数组。

$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 ?>

当我运行一个只吐出数组的测试时,这就是结果, 我想呈现的是 [费城]

[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 个答案:

答案 0 :(得分:298)

您可以像这样访问数组键:

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

答案 1 :(得分:27)

正如Pekka所述

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

您也可以尝试递归函数

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

答案 2 :(得分:6)

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

$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk);
for($i=0;$i<$arraySize;$i++){
    echo "<option value=\"".$keys[$i]."\">".$arrayToWalk[$keys[$i]]."</option>";
}

答案 3 :(得分:5)

foreach($shipmentarr as $index=>$val){    
    $additionalService = array();

    foreach($additionalService[$index] as $key => $value) {

        array_push($additionalService,$value);

    }
}