开发者

using PHP to create multidimensional array from simple JSON array

I have a php query the returns the following JSON format from a table.

[{"memberid":"18", 
"useridFK":"30",
"loginName":"Johnson",
"name":"Frank",
"age":"23",
"place":"School",
},

It needs the following format:

[{"memberid":"18" {
                    "useridFK":"30",
                    "loginName":"Johnson",
                    "name":"Frank",
                    "age":"23",
                    "place":"School",}
                    },

I was told in another question that PHP would work and it looks like "Transversing" might be appropriate, I'm looking to find out what to put in the Php before it returns the JASON.

My Array.plist will look like the following:

  Root:                开发者_如何学运维   Dictionary
       V Rows:            Array
         V Item 0:        Dictionary
            Title:        String          18
          V Children      Array
            V Item 0      Dictionary
              Title       String          30
   etc.

Thanks in advance.


I'm not entirely sure I understand what you want to do. I suppose you want to make the json data into an array in php, and then reorgnize its content to spread over two dimentions?

Php comes with two very nifty functions called "json_decode" and "json_encode" which will allow you to decode and encode json data. You can read more about them here.

A note about "json_decode". Unless you pass on the secondary parameter to the function as TRUE, it will return an object, and not a multi-dimentional array.

Example:

<?php

    $strJsonData = '[
        {"memberid":"18", 
        "useridFK":"30",
        "loginName":"Johnson",
        "name":"Frank",
        "age":"23",
        "place":"School"},

        {"memberid":"19", 
        "useridFK":"36",
        "loginName":"Jones",
        "name":"Bill",
        "age":"34",
        "place":"Work"}
    ]';

    $arrRawJsonData = json_decode( $strJsonData, true );
    # Now $arrRawJsonData contains a two-dimentional array of all your json data.

    $intJsonDataCount = count( $arrRawJsonData );

    for ($i = 0; $i < $intJsonDataCount; $i++)
    {
        $intMemberId = (int) ($arrRawJsonData[$i]['memberid']);
        unset( $arrRawJsonData[$i]['memberid'] );
        $arrJsonData[$intMemberId] = $arrRawJsonData[$i];
    }

    print_r( $arrJsonData );

?>

The above code will result in the following:

Array
(
    [18] => Array
        (
            [useridFK] => 30
            [loginName] => Johnson
            [name] => Frank
            [age] => 23
            [place] => School
        )

    [19] => Array
        (
            [useridFK] => 36
            [loginName] => Jones
            [name] => Bill
            [age] => 34
            [place] => Work
        )

)

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜