English 中文(简体)
PHP json_decode question
原标题:
  • 时间:2009-11-11 08:11:13
  •  标签:
  • php
  • json

i m trying to use json_decode to combine a few json objects and then re-encode it. my json looks like:

{
    "core": {
        "segment": [
            {
                "id": 7,
                "name": "test1" 
            },
            {
                "id": 4,
                "name": "test2" 
            } 
        ] 
    }
}

i have a few of these json objects and would like to combine only the "segement" arrays for each to get something like this:

{
    "segment": [
        {
            "id": 7,
            "name": "test1" 
        },
        {
            "id": 4,
            "name": "test2" 
        } 
    ],
    "segment": [
        {
            "id": 5,
            "name": "test3" 
        },
        {
            "id": 8,
            "name": "test4" 
        } 
    ]
}

right now in my php code, i m decoding the json, storing each "segment" array into a string, and then encoding the json.

public function handleJSON($json){
        $decodeData = json_decode($json);
        $segment =$decodeData->core;
        return $segment;
}

public function formatJSON(){
        $segments = "";
    for ($i = 0; $i < count($json);$i++)
        {
          $segments .= handleJSON($json[$i]);
        }
    echo json_encode($segments);
}

when i do this, i receive an error : Object of class stdClass could not be converted to string

so then i tried using storing them in an array:

public function formatJSON(){
        $segments = array();
    for ($i = 0; $i < count($json);$i++)
        {
          $segments[$i] = handleJSON($json[$i]);
        }
    echo json_encode($segments);
}

this time, i don t get an error, but it stores my entire combined json object in array brackets. how can i have it just return the JSON object, without being encapsulated in an array?

最佳回答

I think one approach would be to take advantage of the second parameter to json_decode, assoc:

"When TRUE, returned objects will be converted into associative arrays."

I find that usually it s easier to deal with associative arrays rather than a stdClass class.

$str =  {
   "core": {
        "segment": [
            {
                "id": 7,
                "name": "test1" 
            },
            {
                "id": 4,
                "name": "test2" 
            } 
        ] 
    }
} ;
print "<pre>";
print_r(json_decode($str));
print "</pre>";
print "<pre>";
print_r(json_decode($str,true));
print "</pre>";

This produces first the Object version, then the associative array:

stdClass Object
(
    [core] => stdClass Object
        (
            [segment] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 7
                            [name] => test1
                        )

                    [1] => stdClass Object
                        (
                            [id] => 4
                            [name] => test2
                        )

                )

        )

)
Array
(
    [core] => Array
        (
            [segment] => Array
                (
                    [0] => Array
                        (
                            [id] => 7
                            [name] => test1
                        )

                    [1] => Array
                        (
                            [id] => 4
                            [name] => test2
                        )

                )

        )

)

I think I would do something like, create new blank array, decode as associative array, grab out the segment members and splice them into the new blank array. So:

$segments = array();
// assuming you had a bunch of items in the $strings array
foreach ($strings as $str) {
  $item = json_decode($str,true);
  $segments = array_merge($item[ core ][ segment], $segments);
}

Now, you can encode this to json like this:

$final_json = json_encode(array( segments =>$segments));
问题回答

Your outer object contains two items named "segment". While this is legal JSON it is not possible to have a PHP object with two different items with the same name.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签