Рубрики
Uncategorized

PHP JSON преобразуется в форму массива

Автор оригинала: David Wong.

Записанный JSON преобразуется в массив классов и методов. Фактически, метод записи может преобразовать большинство структур данных, содержащих строки JSON, в массивы.

class antiTranJson
{
  protected  static function jsonToArray($json)
  {
    if(!is_string($json) || is_null(json_decode($json, true)))
      throw new NotJsonStringException('param is not a json string');
    $deJson = json_decode($json, true);
    return self::toArray($deJson);
  }

  protected  static function stdClassToArray($stds)
  {
    if(is_object($stds))
      throw new NotObjectException('params not object');
    $params = get_object_vars($stds);
    return self::toArray($params);
  }

  protected  static function arrayRToArray($params)
  {
    $tmp = array();
    if(!is_array($params))
      throw new NotArrayException('params not array');
    foreach($params as $k=>$v)
    {
      $tmp[$k] = self::toArray($v);
    }
    //var_dump($tmp);
    return $tmp;
  }

  // Calling this method, data containing JSON can be converted
  public static function toArray($params)
  {
    $tmp = array();
    if(is_string($params) && !is_null(json_decode($params)))
      $tmp = self::jsonToArray($params);
    elseif(is_array($params))
      $tmp = self::arrayRToArray($params);
    // Note here that if $params is an object, the transformation can only be achieved if the included property is readable (public or temporary object property).
    elseif(is_object($params))
      $tmp = self::stdClassToArray($params);
    else
      $tmp = $params;
    return $tmp;
  }

Выше приведен соответствующий код, по крайней мере, на данный момент, вы все еще можете его получить. Если у вас есть хорошие предложения, я надеюсь, что вы сможете обсудить их и добиться прогресса вместе. Спасибо.

Оригинал: “https://developpaper.com/php-json-converts-to-array-form/”