简体   繁体   English

PHP多维数组按键删除元素

[英]PHP multidimensional array remove elements by key

I have a multidimensional Array which looks like this: 我有一个多维数组,看起来像这样:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Edeka Blaschek
        [description] => Lebensmittelmarkt mit Frischfleischtheke und Bäckerei Büsch
        [latitude] => 51.1178
        [longitude] => 6.77537
        [distance] => 0.18105522823916723
    )

[1] => Array
    (
        [id] => 2
        [name] => Autohaus Kopenhagen
        [description] => Peugeot Händler
        [latitude] => 51.1161
        [longitude] => 6.77481
        [distance] => 0.33650698548914737
    )

[2] => Array
    (
        [id] => 10
        [name] => Hallenbad Nievenheim
        [description] => Schwimmbad mit Sauna und Sonnenbänken, sowie kleinem Außenbereich
        [latitude] => 51.1211
        [longitude] => 6.77857
        [distance] => 0.38752806088549746
    )
)

now I want to remove the distance key and value completely from all arrays in the array. 现在,我想从数组中的所有数组中完全删除距离键和值。 It should look like this: 它看起来应该像这样:

    Array
(
[0] => Array
    (
        [id] => 1
        [name] => Edeka Blaschek
        [description] => Lebensmittelmarkt mit Frischfleischtheke und Bäckerei Büsch
        [latitude] => 51.1178
        [longitude] => 6.77537
    )

[1] => Array
    (
        [id] => 2
        [name] => Autohaus Kopenhagen
        [description] => Peugeot Händler
        [latitude] => 51.1161
        [longitude] => 6.77481
    )

[2] => Array
    (
        [id] => 10
        [name] => Hallenbad Nievenheim
        [description] => Schwimmbad mit Sauna und Sonnenbänken, sowie kleinem Außenbereich
        [latitude] => 51.1211
        [longitude] => 6.77857
    )
)

I've tried the solutions mentioned here: PHP - unset in a multidimensional array but they didn't worked for me, what I'm doing wrong here? 我已经尝试过这里提到的解决方案: PHP-未设置在多维数组中,但是它们对我没有用,我在这里做错了什么? Could be very simple sorry but I'm new in PHP. 很简单,很抱歉,但是我是PHP新手。

EDIT: This is the code I tried: 编辑:这是我尝试的代码:

foreach(array_keys($tempArray) as $key) {
   unset($tempArray[$key][5]);
}

And this: 和这个:

foreach($tempArray as $key=>$val){
   unset($val[5]); 
}

$tempArray is the array that I want to change. $ tempArray是我要更改的数组。

try this, 尝试这个,

array_map(function($v){array_pop($v); return $v;}, $array);

Note , array_pop pop the last element of array. 注意 ,array_pop弹出数组的最后一个元素。 if the distance is not the last key, you can use unset() instead 如果距离不是最后一个键,则可以使用unset()代替

   foreach ($mainArray as $key => $mainData){
    foreach ($subArray as $subData){ 
       if($mainData['distance'] == $subData['distance']){
        unset($mainArray[$key]); break; 
  }
   } 
     }

Try this way. 尝试这种方式。 -

我想在php中使用array_values()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM