Search code examples
phpmysqlarraysfind-in-set

php | Convert array to FIND_IN_SET


I'm trying to convert my array to query string. May be you can help me.

My array looks like:

Array
(
    [3] => Array
        (
            [0] => 7
            [1] => 13
            [2] => 1
        )

    [4] => Array
        (
            [0] => 14
            [1] => 2
        )

)

And I'm trying to convert this into:

(FIND_IN_SET('13', vals) || FIND_IN_SET('7', vals) || FIND_IN_SET('1', vals)) AND (FIND_IN_SET('14', vals) || FIND_IN_SET('2', vals))

How can I do this? Thanks!


Solution

  • This may help you.

     [akshay@localhost tmp]$ cat test.php
     <?php
    
     $array = array(array(7,13,1),array(14,2));
    
     function convert_to_string($array)
     {
      return implode(" AND ",array_map(function($v){ return "(".implode(" || ", array_map( function($q){ return sprintf("FIND_IN_SET('%s', vals)",$q);},array_values($v))).")";},array_values($array)));    
     }
    
     echo convert_to_string($array);
    
     ?>
    

    Output

     [akshay@localhost tmp]$ php test.php
     (FIND_IN_SET('7', vals) || FIND_IN_SET('13', vals) || FIND_IN_SET('1', vals)) AND (FIND_IN_SET('14', vals) || FIND_IN_SET('2', vals))