[[+content_image]]
A
A
Alexey2022-02-13 20:25:49
PHP
Alexey, 2022-02-13 20:25:49

How to clear an array recursively?

We have this array:

Array ( [chat_id] => 317373696 [text] => test [reply_markup] => {"inline_keyboard":[[{"text":"category","url":null,"login_url":null,"callback_data":"test2","switch_inline_query":null,"switch_inline_query_current_chat":null,"callback_game":null,"pay":null},{"text":"category 2","url":null,"login_url":null,"callback_data":"test3","switch_inline_query":null,"switch_inline_query_current_chat":null,"callback_game":null,"pay":null}]]} )

It is necessary to remove all empty elements from it, while the reply_markup key is encoded in json, in which it also needs to be cleaned.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Alexey, 2022-02-13
@ichubinets

It's decided.

function isJson($string) 
{
  return is_string($string) && is_array(json_decode($string, true)) ? true : false;
}

function array_clear($array)
{
  foreach ($array as $k => $v) 
  {
    if (is_array($v))
    {
      $array[$k] = array_clear($array[$k]);
    }
    elseif (isJson($v))
    {
      $array[$k] = json_encode(array_clear(json_decode($v, 1)));
    }
    elseif (empty($v)) 
    {
      unset($array[$k]);
    }
  }

  return $array;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question