1

I have following array

[
  ["client_code","contains","12"],
  "and",
  [
    ["trade_name","=","KeyWholesaler"],
    "or",
    ["trade_name","=","Cash&Carry"]
  ],
  "and",
  [
    "!",
    ["state","=","B-BigCantina"],
    ["state","=","B-BigCantina2"]
  ],
  "and",
  ["client_name","contains","M"]
]

I have made a function that recursively echo above array into MySql where query. I know it is messy but It's best I could do to make it work.

  function testing($array) {
    if(is_array($array) && count($array) == count($array, COUNT_RECURSIVE)) {
      $is_not = $_SESSION["NOT"];
      $and = $_SESSION["NOT"] ? " AND" : "";
      echo "`$array[0]` $is_not$array[1] '$array[2]' $and";
      echo "";
    } else if(is_array($array)) {
      echo "(";
      foreach ($array as $key => $value) {
        testing($value);
      }
      echo ")";
      $_SESSION["NOT"] = "";
    } else if($array == "!") {
      $_SESSION["NOT"] = "!";
    } else {
      echo $array;
      echo "";
    }
  }

The output of following function using given array is as

(`client_code` contains '12' and(`trade_name` = 'KeyWholesaler' or`trade_name` = 'Cash&Carry' )and(`state` != 'B-BigCantina'  AND`state` != 'B-BigCantina2'  AND)and`client_code` contains '21' )

Now this function is just echoing following output but I want to get it into a variable.

Sorry for all formatting and bad english. :)

2
  • Is the array format in your control? It is a confusing/imprecise/not-the-best format. here’s an example of a format much easier to parse. Commented Nov 29, 2021 at 7:35
  • It's actually from a plugin called DevExtreme DataGrid Commented Nov 29, 2021 at 7:47

1 Answer 1

2

You can return from within the function and append as string to make a function recursive

  function testing($array) {
    if(is_array($array) && count($array) == count($array, COUNT_RECURSIVE)) {
      $is_not = $_SESSION["NOT"];
      $and = $_SESSION["NOT"] ? " AND" : "";
      return "`$array[0]` $is_not$array[1] '$array[2]' $and";
    } else if(is_array($array)) {
      $val = "";
      foreach ($array as $key => $value) {
        $val =  $val . testing($value);
      }
      $_SESSION["NOT"] = "";
      return "(".$val.")";
    } else if($array == "!") {
      $_SESSION["NOT"] = "!";
    } else {
      return $array;
    }
  }

  echo testing([]);
Sign up to request clarification or add additional context in comments.

Comments

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.