user1240207
user1240207

Reputation: 217

Searching Multi-Dimension Array With Multiple Results

Let's say I have an array and I want to search for a value should return multiple results:

array(2) {
  [0] => array(2) {
    ["id"] => string(2) "1"
    ["custom"] => string(1) "2"
    }
  [1] => array(2) {
    ["id"] => string(2) "2"
    ["custom"] => string(1) "5"
    }
  [2] => array(2) {
    ["id"] => string(2) "3"
    ["custom"] => string(1) "2"
    }
}

I want to search for key custom with value = 2, with the following result:

array(2) {
  [0] => array(2) {
    ["id"] => string(2) "1"
    ["custom"] => string(1) "2"
    }
  [1] => array(2) {
    ["id"] => string(2) "3"
    ["custom"] => string(1) "2"
    }
}

Is this possible without looping through array? Is there such class or built in function for this?

Upvotes: 0

Views: 54

Answers (3)

Stephen
Stephen

Reputation: 18917

the array_filter function is probably what you want.

$array = [
    [
        'id' => '1',
        'custom' => '2'
    ],
    [
        'id' => '2',
        'custom' => '5'
    ],
    [
        'id' => '3',
        'custom' => '2'
    ]
];

$customs = array_filter(
    $array,
    function ($arr) {
        return is_array($arr) && array_key_exists('custom', $arr) && $arr['custom'] === '2';
    }
);

Upvotes: 0

Darren
Darren

Reputation: 13128

You could simply remove the values you don't want by un-setting them from the array:

foreach($array as $key => $item) {
    if($item['custom'] !== 2) {
        unset($array[$key]);
    }    
}

Example


This is an alternative to array_values(), but essentially does it the same way.

Upvotes: 0

Johnny Wong
Johnny Wong

Reputation: 975

You could use:

array_values( array_filter($array, function($item) { return $item['custom'] == 2; }) );

array_values($array) is used to return an array with indexes which is consecutive, i.e. from 0, 1, 2, ... upward.

Upvotes: 1

Related Questions