我有这个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,但我无法使用它。
谢谢!
答案 0 :(得分:0)
我不确定这是否是一个好的解决方案或不是问题 - 同样,不确定在过滤后更改$ 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));
答案 1 :(得分:0)
假设您为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;
}