Help JSON encode PHP

1

Hello I have something like this from a json_encode () in PHP

  ["texto1.","texto2","texto3"]

and I want to get something like this

  "cast": [
    {
      "name": "texto1"
    },
    {
      "name": "texto2"
    },
    {
      "name": "texto3"
    }
  ]

This is the PHP code I have:

<?php
    $json2 = file_get_contents('http://pastebin.com/raw/au4ds3bQ');
    $get2 = json_decode($json2);
    $a = "1";
    $a2 = $get2->data->$a->cast;
    echo json_encode($a2);
?>
    
asked by Guillexd 19.03.2017 в 18:41
source

2 answers

1

you could do something like this

<?php
    $json2 = file_get_contents('http://pastebin.com/raw/au4ds3bQ');
    $get2 = json_decode($json2);
    $a = "1";
    $a2 = $get2->data->$a->cast;
    $items = array();
    foreach ($a2 as $key => $value) {
        $items["cast"][] = array("name" => $value);
    }    
    echo json_encode($items);
?>
    
answered by 19.03.2017 в 19:45
0

In this example I gave you a sample of how it could be done , of course I replaced what you get from pastebin with a json_encoded text.

Basically, $get2 is a non-associative array.

I declare $cast as an empty array

For each of the elements of $get2 , I add an associative array ['name'=>$elemento] to $cast .

The final result is an associative array ['cast'=>$cast];

<?php

$json2= '["texto1.","texto2","texto3"]';

$get2=json_decode($json2);

$cast = [];

foreach($get2 as $elemento) {
    $cast[]=['name'=>$elemento];
}

$arrayfinal= ['cast'=>$cast];

print_r($arrayfinal);
    
answered by 20.03.2017 в 13:07