json_encode with correct format - php

I can't get my json_encode format that I need.
Current Format:
{
"substantiv": [
{"text":"auto"},
{"text":"noch ein auto"}
],
"verben":[
{"text":"auto fahren"}
]
}
What I need:
[
{
"type":"substantiv",
"items": [
{"text":"auto"},
{"text":"noch ein auto"}
]
} , {
"type":"verben",
"items": [
{"text":"auto fahren"}
]
}
]
My current php code:
$data = array();
while($row = $rs->fetch_assoc()){
$tmp = array(
"text" => $row['gtext']
);
$data[$row['type']][] = $tmp;
}
echo json_encode($data);
I have tried a few things but just can't figure it out.

You could try something like this
while($row = $rs->fetch_assoc()){
$data[$row['type']][] = array(
"text" => $row['gtext']
);
}
$result = array();
foreach($data AS $type => $items) {
$result[] = array(
'type' => $type,
'items' => $items
);
}
echo json_encode($result);

What you actually want is this:
[
{
"type": "substantiv",
"items": [
{
"text": "auto"
},
{
"text": "noch ein auto"
}
]
},
{
"type": "verben",
"items": [
{
"text": "auto fahren"
}
]
}
]
which is the output you'll get from Louis H.'s answer's code.

Related

PHP convert CSV to JSON multi level

I have a CSV data looks like this :
ps.csv
id|firstName|lastName|address|extId|extName
001|Kapil|Parames|address01|AA01|AA
002|David|Vuitton|address01|AA02|AA
002|David|Vuitton|address02|BB02|BB
003|Jean|Paul|address01|AA03|AA
And i need an output JSON to look like this :
[
{
"id": "001",
"firstName": "Kapil",
"lastName": "Parames",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA01",
"extName": "AA"
}]
},
{
"id": "002",
"firstName": "David",
"lastName": "Vuitton",
"address": [{
"address": "address01"
},
{
"address": "address02"
}
],
"ext": [{
"extId": "AA02",
"extName": "AA"
},
{
"extId": "BB02",
"extName": "BB"
}
]
},
{
"id": "003",
"firstName": "Jean",
"lastName": "Paul",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA03",
"extName": "AA"
}]
}
]
I can convert it to JSON. But the problem is i would like to add "address" and "extId", "extName" into multi level array if the person already exists in the list.
So following PHP code is working for me :
$csv = file('ps.csv');
$csvArray = [];
foreach ($csv as $line) {
$csvArray[] = str_getcsv($line, '|', ',');
}
$jsonArray = [];
for ($i = 1; $i < count($csvArray); $i++) {
$found = -1;
for ($j = 0; $j < count($jsonArray); $j++) {
if (in_array($csvArray[$i][0], $jsonArray[$j])) {
$found = $j;
}
}
if ($found < 0) {
$jsonArray[] = array(
'id' => $csvArray[$i][0],
'firstName' => $csvArray[$i][1],
'lastName' => $csvArray[$i][2],
'address' => array(
[
'address' => $csvArray[$i][3]
]
),
'ext' => array(
[
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
]
)
);
} else {
$addressArray = array(
'address' => $csvArray[$i][3]
);
$extArray = array(
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
);
array_push($jsonArray[$found]['address'], $addressArray);
array_push($jsonArray[$found]['ext'], $extArray);
}
}
echo '<pre>';
echo json_encode($jsonArray, JSON_PRETTY_PRINT);
echo '</pre>';
Is that correct or is there any other way to do ?

How to modify json key

I need some help to reorder the data in a json file.
I have these few lines :
foreach($rows as $row) {
$data[] = array(
"$row[0]" => array(
"name" => "$row[1]",
"value" => "$row[2]",
"conso" => "$row[3]",
"ml" => "$row[4]"
)
);
}
$data = json_encode($data, JSON_FORCE_OBJECT);
This function allows me to obtain something like this :
This function allows me to obtain something like this :
{
"0": {
"tata": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
}
},
"1": {
"toto": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
}
}
}
I would like something like that :
{
"tata": {
"name": "name_01",
"value": "value_01",
"conso": "conso_01",
"ml": "ml_01"
},
"toto": {
"name": "name_02",
"value": "value_02",
"conso": "conso_02",
"ml": "ml_02"
}
}
Get rid of a layer of array, and specify the key you want. You also don't need to quote all the variables like that.
foreach($rows as $row) {
$data[$row[0]] = array(
"name" => $row[1],
"value" => $row[2],
"conso" => $row[3],
"ml" => $row[4]
);
}
$data = json_encode($data, JSON_FORCE_OBJECT);

Append JSON code to a JSON created from MySQL and PHP

I am trying to create dynamically a JSON from a MySQL, which seems fairly easy with this piece of code I found in this thread Create nested json object using php mysql.
However, I want to add before and after the $json_response some piece of JSON code.
The main code
$result = mysql_query("SELECT * FROM Places ");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['title'] = $row['title'];
$row_array['image_url'] = $row['image_url'];
$row_array['subtitle'] = $row['subtitle'];
$row_array['buttons'] = array();
$id = $row['id'];
$option_qry = mysql_query("SELECT * FROM Places where id=$id");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['buttons'][] = array(
'type' => $opt_fet['type'],
'caption' => $opt_fet['caption'],
'url' => $opt_fet['url'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response, JSON_PRETTY_PRINT);
Produces this JSON
[
{
"title": "Name of the place",
"image_url": "image.jpg",
"subtitle":Additional info",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link "
}
]
},
{
"title": "Name of the place 2",
"image_url": "image2.jpg",
"subtitle":Additional info2",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link 2"
}
]
}
]
I have somehow to add the following code before the already created JSON
{
"version": "v2",
"content": {
"messages": [
{
"type": "cards",
"elements":
And this code in the end
}
]
}
}
Pretty simple:
$final_json = [
"version" => "v2",
"content" => [
"messages" => [[
"type" => "cards",
"elements" => $json_response
]]
]
];
echo json_encode($final_json, JSON_PRETTY_PRINT);
Personally, I'd rename $json_response to $messages for clarity purposes.
While declaring array $json_response = array(); you can actually prepare it with your default values require like
$stdObj=new \stdClass();
$stdObj->version="V2";
$stdObj->content=(object)["messages"=>(object)["type"=>'cards','elements'=>$row_array['buttons']]];
echo json_encode($stdObj, JSON_PRETTY_PRINT);

Add array elements in an array position

How can I add an array to array position:
Something like a:
<?php
$newArr = array('email' => array("id" => "5678", "token" => "fghjk"));
$arr = array(
"auth"=>
array(
'users'=>
array(
'id' =>"456yhjoiu",
'token' => "asdfghjkrtyui678"
)
)
);
somefunction($arr['auth'], $newArr);
I've tried array_push() but it added zero (0) before 'email' instead.~
I'm doing this to get a json output, something like this:
}
"auth": {
"users": {
"id": "456yhjoiu",
"token": "asdfghjkrtyui678"
},
"email": {
"id": "5678",
"token": "fghjk"
}
}
}
but I have this output:
{
"auth": {
"users": {
"id": "456yhjoiu",
"token": "asdfghjkrtyui678"
},
"0": {
"email": {
"id": "5678",
"token": "fghjk"
}
}
}
$data = ['auth' => array_merge($arr['auth'], $newArr)];
or old array notation <= PHP5.3
$data = array('auth' => array_merge($arr['auth'], $newArr));

Array of objects in PHP

I am new to PHP and trying to produce the following json output :
{
"contacts": [
{
"id": "1",
"name": "John Bob",
"email": "john#bob.com"
},
{
"id": "2",
"name": "Johnny Mac",
"email": "johnny#mac.com"
},
.....
]
}
and I have the following PHP code:
$final = array();
foreach ($contacts as $contact)
{
.....
$final[] = array(
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($final, JSON_PRETTY_PRINT);
however, this outputs:
[
{
"id": "1",
"name": "John Bob",
"email": "john#bob.com"
},
{
"id": "2",
"name": "Johnny Mac",
"email": "johnny#mac.com"
},
]
I read over this tutorial and changed $final[] to $final['contacts'] but still couldn't produce the desired json file.
Either:
$final['contacts'][] = array(..);
or:
$contacts_output = array();
foreach ($contacts as $contact) {
$contacts_output[] = array(..);
}
$final = array('contacts' => $contacts_output);
echo json_encode($final, JSON_PRETTY_PRINT);
foreach ($contacts as $contact)
{
.....
$final['contacts'][] = array(
array( //insert all your array in contacts
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}
Try this:
$final = array();
$final['contacts'] = array();
foreach ($contacts as $contact)
{
.........
$final['contacts'][] = array(
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}
$final = array('contacts'=>[]);
foreach ($contacts as $contact)
{
$final['contacts'] []=
array( //insert all your array in contacts
'id' => (string)$id,
'name' => $name,
'email' => $email
);
}

Categories