0

I have a nested JSON. I wanted to convert it to simple json in php

var movies = [{
    "name": "Ice Age 3",
    "place" : "USA",
    "actors" : "cartoon",
    "details": [
        {"language": "English", "year": "2012"}, 
        {"language": "French", "year": "2011"}, 
        {"language": "German", "year": "2013"}
    ],
    "details2": [
        {"language2": "Spanish", "year2": "2015"}, 
        {"language2": "Arabic", "year2": "2016"}, 
        {"language2": "Hindi", "year2": "2017"}
    ]
}];

like this...

  var movies = [
      {"name":"Ice Age 3","place" : "USA", "actors" : "cartoon", "details.language":"English", "details.year":"2012", "details2.language2":"English", "details2.year2":"2015"},
      {"name":"Ice Age 3","place" : "USA", "actors" : "cartoon", "details.language":"French", "details.year":"2011", "details2.language2":"French", "details2.year2":"2016"},
      {"name":"Ice Age 3","place" : "USA", "actors" : "cartoon", "details.language":"German", "details.year":"2013", "details2.language2":"German", "details2.year2":"2017"}
    ];

When i tried this way, i am getting a flat json .

function convert_flatten($array) { 
  if (!is_array($array)) { 
    return FALSE; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $arrayList=convert_flatten($value);
      foreach ($arrayList as $listItem) {
        $result[] = $listItem; 
      }
    } 
   else { 
    $result[$key] = $value; 
   } 
  } 
  return $result; 
} 

This actually is a representation json. Iam looking for a generic answer. Any help will be appreciated

Thanks

3 Answers 3

2

Similar to Prashant's answer...

$movies = '[{
    "name": "Ice Age 3",
    "details": [
    {"language": "English", "year": "2012"},
    {"language": "French", "year": "2011"},
    {"language": "German", "year": "2013"}
    ]
}]';

$movies = json_decode($movies, true);
$out = array();
foreach ( $movies as $movie )   {
    foreach ( $movie['details'] as $movieDetails ){
        $movieDetails['name'] = $movie['name'];
        $out[] = $movieDetails;

    }
}
echo json_encode($out);

Outputs...

[{"language":"English","year":"2012","name":"Ice Age 3"},
    {"language":"French","year":"2011","name":"Ice Age 3"},
    {"language":"German","year":"2013","name":"Ice Age 3"}]

Rather than trying to manipulate the content as some sort of anonymous JSON, this code just works with the data presented. Each element within the original JSON is processed one at a time (potentially allowing multiple movies with the same structure to be present) and just promotes each of the details array elements to the top level in $out (adding the name of the film into this each time).

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think it gets any cleaner than this.
1

try this

     $(function () {
                    var movies = [{
                            "name": "Ice Age 3",
                            "details": [
                                {"language": "English", "year": "2012"},
                                {"language": "French", "year": "2011"},
                                {"language": "German", "year": "2013"}
                            ]
                        }];

                    var obj = JSON.parse(JSON.stringify(movies));
                    var obj2;

                    jsonObj = [];
                    for (var i = 0; i < obj.length; i++) {

                        item = {};
                        obj2 = JSON.parse(JSON.stringify(obj[i].details));
                        for (var j = 0; j < obj2.length; j++) {

                            item ["name"] = obj[i].name;
                            item ["language"] = obj2[j].language;
                            item ["year"] = obj2[j].year;

                            jsonObj.push(item);
                        }
                    }

                    var data = JSON.stringify(jsonObj);

                    alert(data);

                });

1 Comment

try this answers are low value on StackOverflow because they do a poor job of educating the OP and thousands of future researchers. Please never post code-only answers. Please take a moment and explain how your answer works and why it is a good recommendation.
0

You don't need to recurse to do this, this is untested but will give a grounding for what you need;

function flattenMovies($data)
{
    // Get the name of the movie
    $name = $data['name'];
    $return_val = array();
    // For each part of this...
    foreach ($data as $part)
    {
        // If it is an array...
        if (is_array($part))
        {
            // Create a new array for this row and add the movie name
            $add_parts = array("name" => $name);
            // For each of the parts parts...
            foreach ($part as $key => $value)
            {
                // Add this to the row array assoc by key = value
                $add_parts[$key] = $value;
            }
            // Add the row to the return array
            $return_val[] = $add_parts;
            // Blank this row so we know this does not have any "old" info in
            $add_parts = null;
        }
    }
    // Return the flattened array
    return $return_val;
}

All you need to do is traverse the array and add the parts to a single array of values
You may need to add another nesting into the foreach, as I say, untested

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.