按索引子集多维数组

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

我正在尝试通过引用索引对多维数组进行子集化。为了明确起见,我想在“ request_options”中将键的值子集化。这样做的原因是,我计划以后再使用一个for循环来迭代索引值。

问题:

为什么不能子集命名键?

错误:

未定义的偏移量:[repos / git / software / annual_report / xlab / 12_subset_array_by_index_number / index.php在行[xxx]上为0。

$http_components = [
    "services" => [
        1 => [
            "request_options" => [
                "method"       => "GET",
                "header"       => "'Content-Type' => 'application/json'",
                "body_payload" => "'user' => 'x1'"
            ]
        ]
    ]
];

print_r($http_components);

// Subset by name:
print_r($http_components["services"][1]["request_options"]["method"]);

// Attempt subset by index position:
print_r($http_components["services"][1]["request_options"][0]);
php arrays multidimensional-array subset
1个回答
0
投票

您可以使用array_keys()获取关联数组的键,然后对其进行索引以获取相应的命名键。

$key = array_keys($http_components["services"][1]["request_options"])[0];
print_r($http_components["services"][1]["request_options"][$key]);
© www.soinside.com 2019 - 2024. All rights reserved.