用php构建json响应

时间:2016-03-05 21:41:27

标签: php arrays json

我尝试使用复杂的结构处理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个值,但可能更多。

3 个答案:

答案 0 :(得分:0)

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

<tr>
    <th ng-repeat="(key,value) in payoutStructure">{{key}}</th>
</tr>

答案 1 :(得分:0)

假设您的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"
                }
            }
        ]
    }
}

希望这会有所帮助:)

答案 2 :(得分:0)

使用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);