【问题标题】:build json response with php用 php 构建 json 响应
【发布时间】:2016-03-05 21:41:27
【问题描述】:

我曾尝试处理具有复杂结构的 JSON 响应,但多次尝试后我不知道如何管理它。

JSON 响应必须是这样的:

"note": {
      "vote": 3,
      "items":[
        {
            "value": 1,
            "touchArea": {
                "x": 122,
                "y": 173,
                "w": 89,
                "h": 89
            }
        },
        {
            "value": 2,
            "touchArea": {
                "x": 122,
                "y": 283,
                "w": 89,
                "h": 89
            }
        },
        {
            "value": 3,
            "touchArea": {
                "x": 122,
                "y": 390,
                "w": 89,
                "h": 89
            }
        }
      ]

注意:'vote' 是数组的最大值

作为源,我请求 MYSQL,我得到了这个数组 ($touch):

Array ( [0] => V:1,X:122,Y:173,W:89,H:89 [1] => V:2,X:122,Y:283,W:89,H:89 [2] => V:3,X:122,Y:390,W:89,H:89 )

我的问题是:如何使用循环从 PHP 生成这个 JSON 响应,在这个例子中我们只有 3 个值,但可能更多。

【问题讨论】:

  • 每个元素都是字符串吗?例如:V:1,X:122,Y:173,W:89,H:89?

标签: php arrays json


【解决方案1】:

您可以使用以下方法在 json 文件或字符串中编辑和重新保存数据。

<?php
    $sInFile  = 'in2.json';
    $sOutFile = 'out2.json';

    $aDevelopers = array();
    $aArtists    = array();
    $aCooks      = array();

    $sRaw       = file_get_contents( $sInFile );
    var_dump( $sRaw );
    // object
    $oData    = json_decode( $sRaw );
    //array
    $aData    = json_decode( $sRaw, 1 );
    $aNote = $aData[ 'note' ];
    $aItems = $aNote[ 'items' ];
var_dump( $aData );
    $iCountData = count( $aItems );
    // Loops through items and set new values.
    for( $i = 0; $i < $iCountData; ++$i )
    {
        $aItem = $aItems[ $i ];
        $aItem[ 'value' ] = 'newvalue';
        $aItem[ 'touchArea' ][ 'x' ] = 3455;
        $aItem[ 'touchArea' ][ 'y' ] = 43;
        $aItems[ $i ] = $aItem;
    }
    $aNote[ 'items' ] = $aItems;
    $aData[ 'note' ] = $aNote;
var_dump( $aData );
    $sNewJson = json_encode( $aData );

    file_put_contents( $sOutFile, $sNewJson );
?>

【讨论】:

    【解决方案2】:

    假设您来自 MySQL 的结果集是一个字符串数组,正如您的问题所暗示的那样,您需要遍历此结果集,在 , 上拆分字符串,然后在 : 上拆分字符串,然后再按摩数据转换成你想要的结构,最后转换成json。

    根据您提供的信息,以下内容应该对您有用:

    <?php
    
    // your initial result set from mysql - an array of strings
    
    $touch = [
        'V:1,X:122,Y:173,W:89,H:89',
        'V:2,X:122,Y:283,W:89,H:89',
        'V:3,X:122,Y:390,W:89,H:89',
    ];
    
    // map over each element in your result set...
    
    $items = array_map(function($item) {
    
        $array = [];
    
        // first, break each string on `,` to 
        // get an array of elements; e.g:
        // ['V:1', 'X:122', 'Y:173', 'W:89', 'H:89'] etc.
    
        $itemElements = explode(',', $item);
    
        // then, iterate over these elements...
    
        foreach ($itemElements as $itemElement) {
            // explode on `:` and assign as a key value pair
            list($key, $value) = explode(':', $itemElement);
            // then, check the key and add the 
            // value to the array as appropriate
            if ('V' === $key) {
                $array['value'] = $value;
            } else {
                $array['touchArea'][strtolower($key)] = $value;
            }
        }
    
        return $array;
    
    }, $touch);
    
    // then, build the `$note` array...
    
    $note = [
        'note' => [
            'vote'  => count($items),
            'items' => $items,
        ]
    ];
    
    // finally, json encode
    
    echo json_encode($note, JSON_PRETTY_PRINT);
    

    这会产生:

    {
        "note": {
            "vote": 3,
            "items": [
                {
                    "value": "1",
                    "touchArea": {
                        "x": "122",
                        "y": "173",
                        "w": "89",
                        "h": "89"
                    }
                },
                {
                    "value": "2",
                    "touchArea": {
                        "x": "122",
                        "y": "283",
                        "w": "89",
                        "h": "89"
                    }
                },
                {
                    "value": "3",
                    "touchArea": {
                        "x": "122",
                        "y": "390",
                        "w": "89",
                        "h": "89"
                    }
                }
            ]
        }
    }
    

    希望这会有所帮助:)

    【讨论】:

      【解决方案3】:

      array_mapexplodearray_columnmax 函数的解决方案:

      $touch = ["V:1,X:122,Y:173,W:89,H:89", "V:2,X:122,Y:283,W:89,H:89", "V:3,X:122,Y:390,W:89,H:89"];
      
      $result_arr = ["note" => ["vote" => 0, "items" => []]];  // basic structure
      
      array_map(function($v) use (&$result_arr){
          $arr = explode(",", $v);
          $result = [];
          foreach ($arr as $value) {
              $new_arr = explode(":", $value);
              $key = strtolower($new_arr[0]);
              if ($key == "v"){
                  $result["value"] = $new_arr[1];
              } else {
                  $result["touchArea"][$key] = $new_arr[1];
              }
          }
          $result_arr["note"]["items"][] = $result;
      }, $touch);
      
      // getting max vote
      $result_arr["note"]["vote"] = max(array_column($result_arr["note"]["items"], "value"));
      
      $final_json = json_encode($result_arr, JSON_PRETTY_PRINT);
      

      【讨论】:

      • 谢谢帮助。这将适用于 PHP5 吗?原因即 $result_arr = ["note" => ["vote" => 0, "items" => []]];对 PHP5 无效
      • 您忘记了版本。这段代码一般对 PHP5 有效。从 PHP 5.4 开始,您还可以使用短数组语法。从 PHP 5.5 开始,您可以使用出色的函数 array_column。今天升级并“随风而去”。 (我们已经有 PHP 7.0.4)(我的代码没有任何问题)
      • 谢谢。它绝对有帮助!
      • Subs 问题:最终数组是:$appscreen_arr = array("status" => 0, "version" => 0, "screens" => array("veille" => array("background " => 0), "note" => array("vote" => 0, "items" => array(), "background" => 0), "tel" => 0, "fin" => 0 ));有了你的代码和array_map,我只需要用这种格式替换$note_arr?
      • $note_arr 变成 $appscreen_arr。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 2013-07-17
      • 2017-06-05
      相关资源
      最近更新 更多