【问题标题】:PHP Filter a 3D array by the different values of one keyPHP通过一个键的不同值过滤3D数组
【发布时间】:2016-09-11 08:00:04
【问题描述】:

我有这个 3D 数组,我试图通过内部数组中的“类别”字段对其进行过滤,但我无法完全正确。

  Array(
 'type' => 'success',
 'value => array (
     0 => array (
         'id' => 1,
         'joke' => 'Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.',
          'categories' => array());
     1 => array (
          'id' => 2,
          'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.',
          'categories' => array(              
            [0] => nerdy                        
            ));
   );
);

我已尝试使用 array_filter,但无法使其正常工作。

谢谢!

【问题讨论】:

  • 请添加您当前的代码

标签: php arrays array-filter


【解决方案1】:

我不确定这是否是一个好的解决方案 - 同样,不确定在过滤后更改 $x['value'] 的值是否安全,然而,就使用 array_filter 而言,以下内容将对类别值进行过滤:

class Filter {
    private $string = '';

    public function __construct($string2) {
        $this->string = $string2;
    }

    public function catfilter($x) {
        if( in_array( $this->string, $x['categories'] ) ) {
            return true;
        }
    }

    public function filter( $x ) {
        $t = array_filter($x['value'], array( $this, "catfilter"));
        $x['value'] = $t;
        return $x;
    }


}

 $x = array(
 'type' => 'success',
 'value' => array (
     '0' => array (
         'id' => '1',
         'joke' => 'C',
          'categories' => array() ),
     '1' => array (
          'id' => '2',
          'joke' => 'M',
          'categories' => array(          '0' => 'nerdy')  )
   )
);

$f = new Filter('nerdy');
print_r($f->filter($x));

【讨论】:

  • 非常感谢,它确实工作得很好,非常感谢,现在如果我想过滤没有类别的那些,我该怎么办,因为它不会显示它们的代码。
  • 变得凌乱 - 但可以这样做: public function c($x) { if ( empty( $x['categories'] ) ) { return true; } } 公共函数 emptyfilter($x) { $t = array_filter($x['value'], array( $this, "c")); $x['价值'] = $t;返回 $x; }
【解决方案2】:

假设您将 3D 数组命名为 $data,您可以使用:

if($data['type'] == 'success'){
    $results = filter_by_category($data['value'],'nerdy')
}

只需将数组的 2D 部分传递给过滤器函数。

然后,您可以使用以下内容过滤数据集:

function filter_by_category($dataset, $category){
    // define an empty array to populate with the results
    $output = array();

    // iterate the dataset
    foreach($dataset as $row){
        // check if the category we are looking for exists in this row
        if(in_array($category,$row['categories'])){
            // if it does, add it to the output array
            $output[] = $row;
        }
    }
    return $output;
}

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 2019-11-28
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多