Narik
Narik

Reputation: 166

Json Nested arrays to single array using php

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

Upvotes: 0

Views: 363

Answers (3)

Nigel Ren
Nigel Ren

Reputation: 57121

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).

Upvotes: 2

Rajasimman R
Rajasimman R

Reputation: 495

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

                });

Upvotes: 1

anon
anon

Reputation:

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

Upvotes: 0

Related Questions