如何从多维数组中获取特定值?

时间:2019-05-19 16:17:03

标签: php arrays multidimensional-array

我试图了解如何编写PHP语法以从具有定义的给定PHP数组中获取值。

//given definition
$php_array=array(“index1”=>array(“value1”,”value2”,“value3”),
         “index2”=>“value4”,
         “index3”=>array([0]=>“value5”,[1]=>“value6”,
             [2]=>“value7”),
         “index4”=>array([“index5”]=>“value8”,
             [“index6”]=>array(“value9”,”value10”)))

我正在尝试获取“值3”,“值6”和“值” 9。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

您的值在以下变量中:

$php_array['index1'][2];
$php_array['index3'][1];
$php_array['index4']['index6'][0];

答案 1 :(得分:1)

我猜测我们希望循环遍历并提取所需的值,并执行其他操作,我们可以这样做:


在这里,我们有一个主array以及数组内的其他一些数组。它们具有索引(键)和值。

我们期望的输出可以在以下三个地方找到:

$php_array["index1"][2];
$php_array["index3"][1];
$php_array["index4"]["index6"][0];

其中2、1和0是主数组中嵌套数组或内部数组的键:

主阵列

$php_array = array(
    "index1" => ["value1", "value2", "value3"],
    "index2" => "value4",
    "index3" => ["value5", "value6", "value7"],
    "index4" => [
        "index5" => "value8",
        "index6" => ["value9", "value10"],
    ],
);

示例

在这里,我们循环进入具有四个索引的主数组。每当index===到我们的期望值时,程序echo或打印我们的期望值,否则什么都不做:

$php_array = array(
    "index1" => ["value1", "value2", "value3"],
    "index2" => "value4",
    "index3" => ["0" => "value5", "1" => "value6", "2" => "value7"],
    "index4" => ["index5" => "value8", "index6" => ["value9", "value10"]],
);

foreach ($php_array as $key => $value) {
    if ($key === "index1") {
        echo $value["2"];
    }

    if ($key === "index3") {
        echo $value["1"];

    }

    if ($key === "index4") {
        echo $value["index6"]["0"];
    }

}

输出

value3
value6
value9

参考

enter image description here

enter image description here

Video

答案 2 :(得分:0)

我认为我们可以像这样格式化您的数组:

$php_array = array(
    "index1"=>array("value1","value2","value3"),
    "index2"=>"value4",
    "index3"=>array(
        "value5", "value6","value7"
    ),
    "index4"=>array(
        "index5"=>"value8",
        "index6"=>array(
            "value9","value10"
        )
    )
);

$value3 = $php_array['index1'][2];
$value6 = $php_array['index3'][1];
$value9 = $php_array['index4']['index6'][0];