如何获取二维PHP数组的ID?
Array
(
[4] => Test
[6] => This is a test
[9] => 19
[15] => Bla Bla Bla
[appid] => 19746
)
这是我从字符串创建数组的方式:
$str = '4=Test&6=This is a test&9=19&15=Bla Bla Bla&appid=19746';
$result = array();
parse_str($str, $result);
print_r($result);
foreach ($result as $part) {
print_r("id: $id'n"); // I need to get the ID here
print_r("part: $part 'n");
}
使用"双箭头运算符"来实现此目的。
从 PHP 运算符:双箭头和单箭头:
双箭头运算符"=>"用作 阵 列。这意味着它左侧的内容将具有 数组中右侧内容的相应值 上下文。这可用于将任何可接受类型的值设置为 数组的相应索引。索引可以是关联的(字符串 基数(或数字。
所以你的代码将是:
foreach ($result as $id => $part) {
print_r("id: $id'n");
print_r("part: $part 'n");
}
还要考虑oezi的评论:
[...]请注意,您在这里谈论的不是二维数组。 - 它只是一个带有关联键的简单数组。
foreach ($result as $id => $part) {
print_r("id: $id'n"); // Now you get the ID here
print_r("part: $part 'n");
}
foreach ($result as $id => $part) {
print_r("id: $id'n"); // I need to get the ID here
print_r("part: $part 'n");
}