0

I am facing one issue while splitting array by key value. My array looks like below :-

Array
(
[0] => Array
    (
        [product_id] => 6
        [brand_id] => 2
    )

[1] => Array
    (
        [product_id] => 1
        [brand_id] => 1
    )

[2] => Array
    (
        [product_id] => 5
        [brand_id] => 1

    )

)

Now i want to filter split the array based on brand_id. My expected output is like below:-

Array(
[0] => Array(
    [0] => Array
    (
        [product_id] => 6
        [brand_id] => 2
    )
)
[1] => Array(
    [0] => Array
    (
        [product_id] => 1
        [brand_id] => 1
    )
    [1] => Array
    (
        [product_id] => 5
        [brand_id] => 1
  
    )
)
)

My Input array is stored in $proArray variable

My attempt below:-

$brands = array();
    foreach ($proArr as $key => $pro) {
        $brands[] = $pro['brand_id'];
    }
    $brands = array_unique($brands);
    
    $ckey = 0;
    foreach($brands as $brand){
        
    }
user
  • 51
  • 9

2 Answers2

1

One way to do it with simple foreach() loop to push values based on your brand_id like below-

$key = 'brand_id';
$return = array();
foreach($array as $v) {
     $return[$v[$key]][] = $v;
}
print_r($return);

WORKING DEMO: https://3v4l.org/bHuWV

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Code:

$arr = array(
    array(
        'product_id' => 6,
        'brand_id' => 2
    ),
    array(
        'product_id' => 1,
        'brand_id' => 1
    ),
    array(
        'product_id' => 5,
        'brand_id' => 1

    )
);
$res = [];
foreach ($arr as $key => $value)
    $res[$value['brand_id']][] = $value;
$res = [...$res];
print_r($res);

Output:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [product_id] => 6
                    [brand_id] => 2
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [product_id] => 1
                    [brand_id] => 1
                )

            [1] => Array
                (
                    [product_id] => 5
                    [brand_id] => 1
                )

        )

)
Umair Khan
  • 1,684
  • 18
  • 34
  • 1
    There is no reason for the if. All you do is the same thing that the next line does. Create a new array and add the value – Andreas Jun 26 '20 at 13:03