Got a regular array from a form in php.

Array ( [0] => name0 [1] => name1 [2] => name2 [3] => name3 [4] => name4 [5] => name5 [6] => name6) 

It is required to translate it into an associative array and then present the array in json format. An example of a Json file to get:

 { "PC": [ {"name": "name0"}, {"name": "name1"}, ] 
  • Are you sure that nothing is mixed up with the array? What form does this array return? - InDevX 3:17 pm
  • json_encode($array) makes an array $ array json-string - InDevX
  • I receive from the form an array of names <input type = "text" name = "name_node []"> - Valery
  • and what's the point to duplicate the key? What is just not an array of names? can you write what you are doing? - InDevX 3:31 pm
  • I enter into the form the number of required points of the graph, the names of the points are generated, I transfer and receive, respectively, an array of names, then a translation into json format is required, where the first PC key points to the array with names, and the second key is Valery

2 answers 2

You do the conversion to the desired format using the loop and the json_encode() function, then output to the screen, or write to a file.

 $array = ['name0', 'name1', 'name2', 'name3', 'name4']; foreach ($array as $value) { $new['PC'][]['name'] = $value; } echo json_encode($new); // {"PC":[{"name":"name0"},{"name":"name1"} ... {"name":"name4"}]} 
  • one
    Thanks for the help! It works as it should! - Valery

Use json_encode :

 $array = Array(0 => 'name0', 1 => 'name1'); $result = json_encode(array('PC' => $array)); print_r($result); 
  • Read carefully what format is required at the exit from the author of the question. And compare with yours. - Let's say Pie
  • @ Let'ssayPie agree, hurried 😜 - Smolin Pavel
  • look here for another example, the same loop, only with array_map() - sandbox.onlinephpfunctions.com/code/… - Let's say Pie