I know this question was asked already for couple times, I've seen the answers but it already helped me a lot, but i need to solve one more problem regarding to this.
So the question is:
I need to build json file with php.
Here how looks my json file that i need:
{
"fashion":[
{
"alt":"Alisa",
"src":"img/fashion/Alisa/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum001",
"itemNum":0,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa1.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa5.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa7.jpg"
}
]
},
{
"alt":"2-Addis",
"src":"img/fashion/2-Addis/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum002",
"itemNum":1,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/2-Addis/addis1.jpg"
},
{
"alt":"albumImg4",
"src":"img/fashion/2-Addis/addis4.jpg"
}] } ] }
and so on...
I can't find out how to make a list of images inside each album
This is a php function a have
function buildJson(){
$json = json_encode(array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
"album"=>array(
"src"=>"img/fashion/Alisa/alisa1.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa5.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa7.jpg",
),
)
));
echo $json;
}
but I get json like this one:
{
"Fashion": {
"0": {
"src": "img/fashion/Alisa/alisa2.jpg"
},
"1": {
"src": "img/fashion/Alisa/alisa3.jpg"
},
"alt": "Alisa",
"src": "img/fashion/Alisa/kubik.jpg",
"id": "FashionAlbum001",
"itemNum": "0",
"album": {
"src": "img/fashion/Alisa/alisa1.jpg"
}
}
}
How is it possible to fix it?
Thank you!
Please pay more attention to the code you're writing :) Try to decode correct version of your json file and compare it to one you wrote. You should see some differences.
Your problem ir what follows after album key. You are assigning array with only one value to it instead of assigning array of arrays.
This is the way to go:
"album" => array(
array("src" => "img/fashion/Alisa/alisa1.jpg"),
array("src" => "img/fashion/Alisa/alisa5.jpg"),
array("src" => "img/fashion/Alisa/alisa7.jpg"),
),
you trouble in nesting album array
fixed code
function buildJson(){
$json = json_encode(
array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
// nesting error here
"album"=> array(
array("src"=>"img/fashion/Alisa/alisa1.jpg"),
array("src"=>"img/fashion/Alisa/alisa5.jpg"),
array("src"=>"img/fashion/Alisa/alisa7.jpg")
)
)
)
);
echo $json;
}
Related
PHP NEWBIE
[PHP 7.4]
I am trying to refactor some old code.
GOAL: The two JSON must match.
Code snipppet 1: Old JSON code generated from php array
Code snippet 2: New JSON code generated from php array
Objective: Both must match, I am using php unit to compare them. For simplicity, I have removed the testing code.
PROBLEM: Extra set of square brackets, see image below.
I tried Using JSON_FORCE_OBJECT, which removes the square brackets, but introduces {... john: { "0": { "byEmail" ... " and ... "marie": { "1" { "byEmail" ...
(Naming wise: I have used John and marie, but these could be promotions, offers, packages, etc. so ignore the naming please)
SNIPPET 1 - php code
$body = [
"data" => [
"john" => [
"byEmail" => [
"status" => true,
"source" => "my-server",
],
"byPhoneCall" => [
"status" => true,
"source" => "my-server",
]
],
"marie" => [
"byEmail" => [
"status" => true,
"source" => "my-server",
],
"byPhoneCall" => [
"status" => true,
"source" => "my-server",
]
]
]
];
This gets converted to this JSON object:
// SNIPPET 1 - running json_encode()
{
"data": {
"john": {
"byEmail": {
"source": "my-server",
"status": true
},
"byPhoneCall": {
"source": "my-server",
"status": true
}
},
"marie": {
"byEmail": {
"source": "my-server",
"status": true
},
"byPhoneCall": {
"source": "my-server",
"status": true
}
}
}
}
SNIPPET 2:
I am creating this data structure dynamically now, because future requirement may have johnByPost, johnByFax, etc.:
//my-file-dynamic-generation.php
public function constructArray($johnByEmail=null, $johnByPhone=null, $marieByEmail=null, $marieByPhone=null) {
$body = [ "data" => ["john" => [], "marie" => []]];
if ($johnByEmail !== null) {
array_push($body["data"]["john"], $this->createKeyValuePair("byEmail", $johnByEmail));
}
if ($johnByPhone !== null) {
array_push($body["data"]["john"], $this->createKeyValuePair("byPhoneCall", $johnByPhone));
}
if ($marieByEmail !== null) {
array_push($body["data"]["marie"], $this->createKeyValuePair("byEmail", $marieByEmail));
}
if ($marieByPhone !== null) {
array_push($body["data"]["marie"], $this->createKeyValuePair("byPhoneCall", $marieByPhone));
}
return $body;
}
// HELPER func
function createKeyValuePair($title=null, $status=null, $source="my-server") {
return [
$title => [
"status" => $status,
"source" => $source,
]
];
}
JSON - OUTPUT
I have tried to use json_encode($data, JSON_FORCE_OBJECT)
That resulted me to get an extra key, which I don't want (I got .... [0] => 'marie' => ... [1] => 'john'
Appreciate reading this, thanks!
You are creating a new array inside the function createKeyValuePair() (probably to add the key). You could use the function the create the content only, and create the key inside the function constructArray() :
$body["data"]["john"]["byEmail"] = $this->createKeyValuePair($johnByEmail);
and the function :
function createKeyValuePair($status = null, $source = "my-server"): array
{
return [
"status" => $status,
"source" => $source,
];
}
I'm getting via url querystring variables like:
myserver_state=1&myserver_running=2&myserver_mem=3
Currently i'm adding to an existing json like:
{
"key1": "1",
"key2": "2",
"key3": "3",
"myserver_state": "1",
"myserver_running": "2",
"myserver_mem": "3"
}
And i really want it like this:
{
"key1": "1",
"key2": "2",
"key3": "3",
"myserver": {
"state": "1",
"running": "2",
"mem": "3"
}
}
I'm using this to load them:
$formdata = array(
'state'=> $_POST['state'],
'uassip'=> $_POST['uassip'],
'uassipport'=> $_POST['uassipport'],
'c_uacminrtpport'=> $_POST['c_uacminrtpport'],
'c_uacmaxrtpport'=> $_POST['c_uacmaxrtpport'],
'c_cps'=> $_POST['c_cps'],
'c_totalcalls'=> $_POST['c_totalcalls'],
'c_maxchannels'=> $_POST['c_maxchannels'],
'c_duration'=> $_POST['c_duration'],
'c_to'=> $_POST['c_to'],
'c_uacxml'=> $_POST['c_uacxml']
);
echo "fromdata: <br>"; echo var_dump($formdata) . "<br><hr>";
if(file_put_contents('testconfig.json', json_encode($formdata) )) echo 'OK';
else echo 'Unable to save data in "testconfig.json"';
Many thanks!
EDIT:
following comments i tried:
status.php?server1[current_state]=10
this actually works to:
"c_uacxml": "telnyx-uac-invite-ok.xml",
"server1": {
"current_state": "10"
}
}
Which is great, BUT, if i then want to add an element like this:
status.php?server1[current_mem]=1
This actually REPLACES the whole server1
"c_uacxml": "telnyx-uac-invite-ok.xml",
"server1": {
"current_mem": "10"
}
}
and i lose the already existing current_state
Just use multidimensional array within your URL like:
test.php?key1=1&key2=2&myserver[state]=1&myserver[running]=2&myserver[mem]=3
so easy script
<?php
echo '<pre>';
echo json_encode($_GET, JSON_PRETTY_PRINT);
will give you
{
"key1": "1",
"key2": "2",
"myserver": {
"state": "1",
"running": "2",
"mem": "3"
}
}
of course, if required you can use also POST request with the same naming rules.
in order to create a nested JSON object, you need to create an array within an array.
E.g.
$example = [
'key1' => 'foo',
'key2' => 'bar',
'key3' => [
'subkey1' => 'foo',
'subkey2' => 'bar',
],
];
When running it through json_encode(), it will result in
{
"key1": "foo",
"key2": "bar",
"key3": {
"subkey1": "foo",
"subkey2": "bar"
}
}
Also it's not necessary to load form data like this –
$formdata = [
'state' => $_POST['state'],
'uassip' => $_POST['uassip'],
'uassipport' => $_POST['uassipport'],
'c_uacminrtpport' => $_POST['c_uacminrtpport'],
'c_uacmaxrtpport' => $_POST['c_uacmaxrtpport'],
'c_cps' => $_POST['c_cps'],
'c_totalcalls' => $_POST['c_totalcalls'],
'c_maxchannels' => $_POST['c_maxchannels'],
'c_duration' => $_POST['c_duration'],
'c_to' => $_POST['c_to'],
'c_uacxml' => $_POST['c_uacxml'],
];
Since the $_POST already contains a structure that you are trying to recreate. You can simply assign the post data to a new varaible.
On another note, I highly recommend you to check out PSR PHP standards, they will greatly help to improve code readability and your code structure :) https://www.php-fig.org/psr/
I need to create json with multiple levels via PHP.
{
"accident": {
"dateTime": "2015-08-08T16:12:08",
"desc": "string"
},
"calculationInput": {
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
"wageRates": {
"labourRate1": 10,
"labourRate2": 11,
"labourRate3": 22,
"labourRate4": 33,
"labourRateD": 44,
"paintRate": 55
}
},
"caseNumber": "F4Q",
"vehicle": {
"adminData": {
"firstRegDate": "2015-07-08",
"numberPlate": "MI214AF"
},
"identification": {
"vin": "VF7S6NFZF56215577"
},
"owner": {
"city": "Praha",
"country": "CZE",
"email": "mail#mail.com",
"name": "Fero Taraba",
"phone": "777111222",
"phone2": "999555333",
"postCode": "07101",
"street": "Kukureliho 18"
}
}
}
I actuyltry this and it's possible for me to create single level json, with other words:
$data = array (
"caseNumber" =>"F4Q"
);
and then just easy:
$data_json= json_encode($data);
But can someone explain me how can I do this second or even 3th level tree to convert to JSON?
I will really appriciate your help guys. Thanks
EDIT:
Most of the answers really lead me right way, only problem now is this part:
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
where there is [ ] which represent some list of blockCodes. Any idea what to do with this ? :)
What is your question exactly?
You can create a array and then just encoding it to json?
$data = array(
'Key 1' => array(
'Key 2 - Key 1' => array(
'Key 3 - Key 1' => array()
)
)
);
echo json_encode($data);
Just use associative arrays
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
print out
{"caseNumber":"F4Q","vehicle":{"adminData":{"firstRegDate":"2015-07-08","numberPlate":"MI214AF"},"identification":{"vin":"VF7S6NFZF56215577"}}}
Use associative Arrays:
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
echo json_encode($data)
you get your brackets by putting an additional array around your object.
$data = array("idBlockCodes" => array(
array(
"code" => 51,
"value" => 1
)
)
);
print json_encode($data);
For you to convert all of your data to array:
You must first use json_encode();
$a = json_encode($yourData);
And then decode it:
$b = json_decode($a, true);
echo '<pre>';
print_r($b); //print it
It displays associated arrays with it
I am creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:
{
"sections": {
"content": [{
"para": "Hello"
}]
}
}
I tried using this code:
$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));
But I received this instead:
{
"sections": [{
"content": [],
"0": {
"para": "Hello"
}
}]
}
If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?
If I understood your intentions correctly, here's the array structure you're aiming for:
array("sections" => array(
"content" => array("para" => "Hello"),
));
However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.
Here's an array of content objects:
$content = new stdClass();
$content->para = 'hello';
array("sections" => array(
"content" => array($content),
));
To add arrays of contents:
array("sections" => array(
"content" => array(
array("para" => "Hello"),
array("para" => "Hello"),
array("para" => "Hello"),
),
));
You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:
$content = array();
for (i=0; i <3; i++) {
$content[] = array('para' => 'hello');
}
json_encode(array("sections" => array(
"content" => array($content),
)));
To convert that to JSON, put your array inside a json_encode() call.
$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);
will give the result in desired format
I am having issues with validating the output of my json_encode() function.
I am pulling in an XML feed with cURL, converting it into an array, and converting that array into JSON with json_endode(). Ill spare you the cURL stuff:
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json = str_replace('\/','/',json_encode($article));
echo $json;
}
Which is giving me a JSON readout of:
{
"articleResult": {
"articleId": "0001",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
{
"articleResult": {
"articleId": "0002",
"title": "Some title",
"subhead": "Some engaging subhead",
"tweet": "Check out this tweet",
"publishedDate": "January 1st, 1970",
"image": "http://www.domain.com/some_image.jpg"
}
}
This will give me a JSONLint error saying:
Parse error on line 10:
..._120x80.jpg" }}{ "articleResult
---------------------^
Expecting 'EOF', '}', ',', ']'
So naturally I will add in the comma, which gives me an End of File expectation:
Parse error on line 10:
..._120x80.jpg" }},{ "articleResu
---------------------^
Expecting 'EOF'
I am new to JSON, but I have checked the website and a few resources for proper JSON formatting and structure, and from what I can see my readout is following the guidelines. Any pointers?
Resources I've checked:
JSON.org naturally
Wikipedia has well documented page
W3Resource Had a good explanation of structure.
JSONLint
You were encoding 2+ objects into json string, you need [ ] to wrap them
the correct syntax is
[
{ /* first object */ }
, { /* second object */ }
, { /* third object */ }
]
the things you need to look out are
[ ] wrap
separate objects by comma
Solution
$json = array();
foreach ($xmlObjects->articleResult as $articleResult) {
$article = array(
"articleResult" =>
array(
'articleId' => (string)$articleResult->articleId,
'title' => (string)$articleResult->title,
'subhead' => (string)$articleResult->subhead,
'tweet' => (string)$articleResult->tweet,
'publishedDate' => (string)$articleResult->publishedDate,
'image' => (string)$articleResult->image
),
);
$json[] = $article;
}
echo json_encode($json);