【发布时间】:2023-03-16 21:35:01
【问题描述】:
在多维数组中获取数组键是一个有趣的情况。
我知道如何使用 foreach 获取数组值,但是如何获取键值并插入到数据库中??
这是我的代码:
//Array
$BookingInfo = array(
"115"=>array(
"date"=>array(
"15/12/2014"=>array(//need to get the date but not in here
array(
//need to get the date in here!!
"from"=>2,
"to"=>5,
"user"=>"Ella",
"userid"=>"b2111"
),
array(
"from"=>5,
"to"=>7,
"user"=>"Johnson",
"userid"=>"a2413"
)
),
"16/12/2014"=>array(
array(
"from"=>4,
"to"=>8,
"user"=>"Peter",
"userid"=>"g531"
)
),
"17/12/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Chris",
"userid"=>"h024"
),
array(
"from"=>3,
"to"=>6,
"user"=>"Jennifer",
"userid"=>"f314"
)
),
"20/12/2014"=>array(
array(
"from"=>1,
"to"=>5,
"user"=>"Raymond",
"username"=>"r362"
)
),
"21/12/2014"=>array(
array(
"from"=>1,
"to"=>6,
"user"=>"Amy",
"username"=>"a754"
)
),
"23/08/2014"=>array(
array(
"from"=>2,
"to"=>4,
"user"=>"Amy",
"userid"=>"m432"
)
)
)
)
);
foreach 代码:
foreach($BookingInfo as $roomNumber => $value){
foreach($value as $id => $val){
foreach($val as $bookDate => $array){
foreach($array as $key => $detail){
foreach($detail as $period =>$info){
//get the $bookDate here
//if I get the "$bookDate" here, it shows the result with repeating 3 times, how can I solve it??
}
}
}
}
}
我想得到“15/12/2014”2次,因为有两个会员预订,“16/12/2014”1次,怎么办?感谢您的帮助。
【问题讨论】:
-
感谢 Verhaeren。是 foreach($BookingInfo[$roomNumber][$id] as $bookDate => $array) 在第三个 foreach 吗?谢谢。
-
Verhaeren,我已经更新了数组。谢谢。
-
@Verhaeren,使用
foreach($value as $id => $val){有什么问题?它比您的建议更容易阅读。并且 2 是等效的,前提是您只从数组中读取。如果您担心对数组的修改,那么通过引用分配会更简洁,即将第一个 foreach 更改为foreach($BookingInfo as $roomNumber => &$value) {,但我认为这不是这个特定用例的要求。
标签: php arrays multidimensional-array foreach