按子数组键值剪切数组

时间:2014-09-26 20:13:19

标签: php multidimensional-array foreach

我有这个数组

array(5) {
  [0]=>
  array(5) {
    ["id"]=>
    int(1411667077)
    ["nachricht"]=>
    string(13) "iiiiiiiiiiiii"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "25.09.2014 19:44"
    ["deleted"]=>
    string(0) ""
  }
  [1]=>
  array(5) {
    ["id"]=>
    int(1411701734)
    ["nachricht"]=>
    string(2) "dd"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "26.09.2014 05:22"
    ["deleted"]=>
    string(0) ""
  }
  [2]=>
  array(5) {
    ["id"]=>
    int(1411701737)
    ["nachricht"]=>
    string(6) "swfsfs"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "26.09.2014 05:22"
    ["deleted"]=>
    string(0) ""
  }
  [3]=>
  array(5) {
    ["id"]=>
    int(1411701739)
    ["nachricht"]=>
    string(7) "egwegeg"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "26.09.2014 05:22"
    ["deleted"]=>
    string(0) ""
  }
  [4]=>
  array(5) {
    ["id"]=>
    int(1411742201)
    ["nachricht"]=>
    string(3) "sss"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "26.09.2014 16:36"
    ["deleted"]=>
    string(0) ""
  }
}

我想剪切id 1411701737的位置,所以我尝试了:

foreach($array as $arr => $sub_arr)
{
    if $sub_arr['id'] == 1411701737
    {
         break;
    }
 }

我知道我需要在foreach中创建一个全新的数组,但是不是可能有一个内置函数吗?

2 个答案:

答案 0 :(得分:0)

$new = array();
foreach($array as $k) {

   if($k['id'] == 1411701737) break;
   array_push($new, $k);

}

var_dump($new);

Mooseman的答案可能是一种更快的方法,因为它不依赖于PHP函数调用将数组放入新数组中。但是,除非你在一组100k +以上的数组中这样做,否则它确实无关紧要。

答案 1 :(得分:0)

$arr_new = array(); //Define a new array
foreach($arr_old as $a) { //Loop through the old one
   if($a['id'] === 1411701737) break; //If the value of id matches, leave the foreach loop
   $arr_new[] = $a; //Else, copy this array to the new array
}
print_r($arr_new); //Print the new array