Search code examples
phparraysmultidimensional-arraygroupingarray-filter

Separate rows in a 2d array into two groups based on string in row


I need to group rows in a multidimensional array by the value of a sub-array which is not consistently found in the same column.

$array = [
    147 => [4, 'req'],
    199 => ['5', 'opt'],
    212 => [2, 5, 'req']
];

It needs to be split into these arrays.

Array 1:

[
    147 => [4, 'req'],
    212 => [2, 5, 'req'],
]

Array 2:

[
    199 => ['5', 'opt'],
]
  

I know of array_filter(), but can´t figure out the function inside array_filter() that gives me the desired result.

I tried

$req = array_filter($my_array, function ($v, $k) {
    return $v == 'req';
}, ARRAY_FILTER_USE_BOTH);

I also tried

function filter_my_array($my_array, $search_term) {
  $new_array = array();
  foreach ($my_array as $subarray) {
    if (in_array($search_term, $subarray)) {
       $new_array[] = $subarray;
    }
  }
  return $new_array; 
} 
         
$req = filter_my_array($array, 'req');

Both approaches do not work.


Solution

  • You can create two arrays with the help of filtering by necessary values. You can use array_filter function to it, but you should find a necessary value in each element that passed to array_filter function.

    For example, finding 'req' value

    $req = array_filter($my_array, function ($v) {
        return in_array('req', $v);
    });
    

    For example, finding 'opt' value

    $opt = array_filter($my_array, function ($v) {
        return in_array('opt', $v);
    });
    

    I used in_array function to finding values because each element is an array that has different quantity of elements