[英]Remove/unset every other key in multidimensional array but preserve keys
I have a long multidimensional array with timestamps as keys which contain arrays of values. 我有一个长的多维数组,带有时间戳作为键,其中包含值的数组。 Something like this but with more timestamps: 像这样但带有更多时间戳的东西:
array(3) {
[1502609400]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(100)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(50)
}
}
[1502611200]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(200)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(150)
}
}
[1502613000]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(500)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(250)
}
}
How can I remove every every second array of the array without losing the keys as timestamp? 如何在不丢失键作为时间戳的情况下删除数组的每个第二个数组? So I end up with this: 所以我最终得到了这个:
array(3) {
[1502609400]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(100)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(50)
}
}
[1502613000]=>
array(2) {
["Item1"]=>
array(1) {
["PRICE"]=>
float(500)
}
["Item2"]=>
array(1) {
["PRICE"]=>
float(250)
}
}
If I use a for loop and unset every second key I lose all the keys and end up with 0, 1, 2 etc. instead of the timestamp. 如果使用for循环并取消设置第二个键,则会丢失所有键并以0、1、2等(而不是时间戳)结尾。
In a loop, check for index and unset every second element: 在循环中,检查索引并取消设置第二个元素:
You can use custom $index
variable, like this: 您可以使用自定义$index
变量,如下所示:
$index = 0; // points to first element
foreach ($array as $key => $value) {
if ($index % 2 != 0) { //check for un-even
unset($array[$key]);
}
$index++; // move pointer to next element
}
$i=1 // where the key to remove
$x=0; //loop to determine the key position
foreach ($array as $key=>$value){
if($x==$i){
unset($array[$key]);
}
$x++;
}
In that kind of case, a simple foreach can be more efficient perfwise than a standard function : 在这种情况下,简单的foreach可能比标准函数更高效。
foreach ($array as $key => $val) {
if (array_key_exists('Item2', $val)) {
unset($val['Item2']);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.