如何在PHP中使用带有foreach的数组

时间:2016-02-19 02:48:14

标签: php

我尝试在PHP中使用数组,通过查找索引和键作为foreach。 例如,我希望 $ k [" ab"] $ ro [" hh"] 但我可以'得到它

<?php
$data = array(
    "test"=>array(
        "some"=>"d",
        "hello"=>"e",
        "ther"=>"a"
    ),
    "ab"=>array(
        "ad"=>"tt",
        "de"=>"jj",
        "hh"=>"uu")
    );
    foreach($data as $k=>$ro){
          var_dump($k);
    } 
?>

2 个答案:

答案 0 :(得分:2)

您最好学习多维数组的结构。

<?php
$data = array(
    "test"=>array(
        "some"=>"d",
        "hello"=>"e",
        "ther"=>"a"
    ),
    "ab"=>array(
        "ad"=>"tt",
        "de"=>"jj",
        "hh"=>"uu")
);
foreach($data as $key => $values){
    echo $key; // which will output "test", "ab", which are the array keys
    print_r($values); // which will output the contents of the inner array (e.g. array("some"=>"d","hello"=>"e","ther"=>"a") )

    // to obtain the inner array values, you can either use another foreach...
    foreach($values as $k => $v) {
       echo $k . ', ' . $v; // which will output "ad, tt", etc
    }
    // ...or specify which key to obtain
    if(isset($values["ad"])) { echo $values["ad"]; } 
    // isset() must be used, as the key does not exist in 1st inner array
}
?>

答案 1 :(得分:1)

请尝试下面的内容:

<?php
$data = array(
    "test"=>array(
        "some"=>"d",
        "hello"=>"e",
        "ther"=>"a"
    ),
    "ab"=>array(
        "ad"=>"tt",
        "de"=>"jj",
        "hh"=>"uu")
    );
    foreach($data as $k=>$ro){
        if($k == "ab"){
            echo "<pre>";
            print_R($ro);
            echo 'HH Value ===> '.$ro['hh'];
        }
    } 
?>

想要获得所有价值和关键点以下各项:

foreach($data as $k=>$ro){
        foreach($ro as $inner_key => $inner_value){
            echo "<br/> Key ===> ".$inner_key."==== value =====>".$inner_value;
        }

    }