我有如下数组的PHP数组,我想根据键“类型”值提取数组。我的意思是例如在下面的代码中想要基于
提取'type' => '1'
'type' => '2' ( There are two arrays for this condition)
'type' => '22' ( There are two arrays for this condition)
为此,我将转向for循环中的每个元素并梳理相关的元素。但有没有直接的功能呢?
像array.search(类型值2)那样给出相关的两个条目..? (因为我有很多这样的类型)
感谢您的帮助
array
0 =>
array
'type' => string '1'
'code' => string '1'
'total_count' => string '200'
'car_count' => string '4'
1 =>
array
'type' => string '2'
'code' => string '52160'
'total_count' => string '100'
'car_count' => string '2'
2 =>
array
'type' => string '2'
'code' => string '26'
'total_count' => string '30'
'car_count' => string '15'
3 =>
array
'type' => string '20'
'code' => string '6880'
'total_count' => string '4'
'car_count' => string '0'
4 =>
array
'type' => string '21'
'code' => string '256'
'total_count' => string '10'
'car_count' => string '5'
5 =>
array
'type' => string '22'
'code' => string '20'
'total_count' => string '100'
'car_count' => string '8'
6 =>
array
'type' => string '22'
'code' => string '25'
'total_count' => string '120'
'car_count' => string '9'
答案 0 :(得分:4)
如果数组元素匹配,您可以在函数内制定条件,返回true
,如果不匹配,则返回false
。
然后将其用作array_filter
Docs的回调。
示例(类型必须是整数2):
function myMatch($element)
{
return $element['type'] === 2;
}
$values = array_filter($array, 'myMatch');
根据您的需要修改功能。输入将是单个元素。
或者如果您希望使用指定的约束(Demo)调用数组上的某个接口:
<?php
$array = array(
array('type' => '1'),
array('type' => '2'),
array('type' => '22'),
);
$compareValue = 'type';
$startsWith = '2';
$array = new OArray($array);
$compareValue = function($v) use ($compareValue)
{
return (string) $v[$compareValue];
};
$startsWith = function($value) use ($startsWith)
{
return 0 === strpos($value, $startsWith);
};
$constraint = function($element) use ($compareValue, $startsWith)
{
return $startsWith($compareValue($element));
};
var_dump(
$array->filter($constraint)
);
class OArray
{
/**
* @var Array
*/
private $array;
public function __construct($array)
{
$this->array = $array;
}
/**
* function based filter
*/
public function filter($function)
{
if (!is_callable($function))
throw new InvalidArgumentException('Invalid function given.');
return array_filter($this->array, $function);
}
}
但更优雅的变体是在数组上使用FilterIterator,它可以使参数更好,更可重用(Demo):
<?php
$array = array(
array('type' => '1'),
array('type' => '2'),
array('type' => '22'),
);
$filter = new ArrayElementStartsWithFilter($array, 'type', '2');
var_dump($filter->filter());
class ArrayElementStartsWithFilter extends FilterIterator
{
private $what;
private $with;
public function __construct(array $array, $what, $with)
{
$this->what = $what;
$this->with = $with;
parent::__construct(new ArrayIterator($array));
}
public function accept()
{
$element = $this->getInnerIterator()->current();
return !empty($element[$this->what])
&& 0 === strpos($element[$this->what], $this->with)
;
}
public function filter() {
return iterator_to_array($this);
}
}