Search code examples
phparraysarray-filterarray-column

Filter array based on the exploded key value


I have an associated array,

$array2 = array(
    array('customer_id' => '01', 'categories' => '',),

     array('customer_id' => '02', 'categories' => '',),

     array('customer_id' => '03', 'categories' => '20,26,18',),

     array('customer_id' => '04', 'categories' => '45,118',),
);

I need to fetch the arrays with category value 18. I have exploded the category values and checked them in array_filter.

function testCategories($var)
{
    $like = 18;
    $categoryArray = array_column($var, 'categories');
    foreach($categoryArray as $ca){
    $caEplode = explode(',', $ca);
        foreach($caEplode as $cae){

            return($cae == $like);
        }
    }
}

print_r(array_filter($array2,"testCategories"));

But I am returning an empty string. Can any one please help me?


Solution

  • I didn't use array_filter but this might be fine

    <?php
        $array2 = array(
            array('customer_id' => '01', 'categories' => '',),
    
             array('customer_id' => '02', 'categories' => '',),
    
             array('customer_id' => '03', 'categories' => '20,26,18',),
    
             array('customer_id' => '04', 'categories' => '45,118',),
        );
    
        function testCategories($var)
        {
            $like = 18;
            foreach($var as $ca){
                $caEplode = explode(',', $ca['categories']);
                foreach($caEplode as $cae){
                    if($cae == $like)
                      $result[] = $ca;
                }
            }
            return $result;
        }
    
        print_r(testCategories($array2));
    
    
         ?>
    

    result

    Array ( [0] => Array ( [customer_id] => 03 [categories] => 20,26,18 ) )