1

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!

3
  • 1
    How are you trying to build this query? What API are you using? Commented May 15, 2015 at 9:20
  • ^ Besides that; Have you tried something to get to your goal yourself? Commented May 15, 2015 at 9:20
  • What I have tried didn't work... Commented May 15, 2015 at 9:38

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Bear in mind that if any of the values in the array are user-supplied, then this is ripe for SQL injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.