如何访问二维数组中的数据[重复]

问题描述 投票:0回答:2

我尝试通过查找索引和键作为 foreach 在 PHP 中使用数组。 例如我想得到 $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);
    } 
?>
php arrays
2个回答
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
投票

请尝试以下:

<?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;
        }

    } 
© www.soinside.com 2019 - 2024. All rights reserved.