过滤器数组在关联值上重复

时间:2012-03-11 19:53:11

标签: php

我有一个阵列:

(
[0]
   (
      [room_num] => 1
      [is_event] => true
      [date] => '01/01/2013'
   )
[1]
   (
      [room_num] => 2
      [is_event] => false
      [date] => ''
   )
[2]
   (
      [room_num] => 3
      [is_event] => false
      [date] => ''
   )
[3]
   (
      [room_num] => 1
      [is_event] => false
      [date] => ''
   )
)

我想要做的是过滤结果,以便is_event = true取代is_event = false。我返回的数组看起来像:

(
[0]
   (
      [room_num] => 1
      [is_event] => true
      [date] => '01/01/2013'
   )
[1]
   (
      [room_num] => 2
      [is_event] => false
      [date] => ''
   )
[2]
   (
      [room_num] => 3
      [is_event] => false
      [date] => ''
   )
)

类似于array_unique,除了某个值。

这是否有内置功能?

2 个答案:

答案 0 :(得分:0)

没有内置功能

你必须循环并检查自己

答案 1 :(得分:0)

好吧,因为没有内置函数我写出来,循环和所有。

万一你好奇如何:

// @filter is an array of data where (in my case) is_event=0, thus to be filtered
// @keep is an array of data where (again in my case) is_event=1 (data to be kept)
// @$key is the key we will make our comparisons with (in this case is_event)

function filter_assoc_on_key($filter,$keep,$key){

        $tempArr = array();
        $removeArr = array();
        // make an array of the array entries with values matching my key
        foreach($keep as $keeper){
            array_push($tempArr,$keeper[$key]);
        }
        // loop the array i want to filter and add the entries matching my key to the $removeArr
        for($i=0;$i<count($filter);$i++){
            if(in_array($filter[$i][$key],$tempArr)){
                array_push($removeArr,$filter[$i]);
            }
        }
        // merge the arrays so that I have all my values in one place
        $newArr = array_merge($filter,$keep);
        // get the values that are unique
        $goodArr = array_diff_assoc($newArr,$removeArr);

        return $goodArr;
    }