Массивы PHP. Получение всех связанных с ними значений

У меня есть массив массивов PHP, как показано ниже, и я хочу извлечь массивы на основе значения ключа «type». Я имею в виду, например, в приведенном ниже коде хотите извлечь на основе

'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' 

Вы можете сформулировать свое условие внутри функции, которая возвращает true если элемент массива соответствует, а false нет.

Затем вы используете его как обратный вызов с документами array_filter .

Пример (тип должен быть целым числом):

 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); } }