PHP foreach循环键值


135

我正在运行此数据库调用以获取多维数组,我试图获取每个数组的键,但是当我尝试将其显示为空白或数组时。

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

Answers:


381

您可以这样访问数组键:

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

此方法仅返回“数组”
matthewb

如果回显$ key,该怎么办?没事 如果您在Philadelphia作为键的数组上运行它,则不会。你能显示一些代码吗?
Pekka

这行得通,我的mysql语句也有一个小问题,但是我将它与您的解决方案一起使用,谢谢。
matthewb

32

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

8

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

$keys      = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk);

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

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

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

        array_push($additionalService,$value);

    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.