Make a JSON file with multiple same format using PHP - php

Fist of all i would like to tell I am a beginner for JSON. I would like to know how to make a following format JSON using PHP. I think I want to use loop function.
Example:
[ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ]
In my PHP file have $VALUE variable in different places. I want know id and name values store method to make this JSON. I can not use $VALUE1, $VALUE2 etc.
Some places have following $VALUE variable with some data. is it method right to make this JSON
$VALUE = array("id" => "1", "name" => "test1");
$VALUE = array("id" => "3", "name" => "test3");

I think that json_encode() and json_decode() will help you.
$array = [
["id" => 1, "name" => "test1"],
["id" => 2, "name" => "test2"],
["id" => 3, "name" => "test3"],
["id" => 4, "name" => "test4"]
];
$jsonEncoded = json_encode($array);
$jsonDecoded = json_decode($jsonEncoded);
var_dump("Json Encoded array to string:", $jsonEncoded);
var_dump("Json Decoded string to array:", $jsonDecoded);
In order to update (add/update or remove) the encoded json array you need to decode first and encode again. There is no other way to add an "object" to an already encoded json string.
You can always check the official documentation for more information.
json_encode
json_decode

You can do it like this if you wanted : using arrays and with cast to an object
$json_php_oupout = [
(object)["id"=>"1", "name"=>"test1"],
(object)["id"=>"2", "name"=>"test2"],
(object)["id"=>"3", "name"=>"test3"],
(object)["id"=>"4", "name"=>"test4"],
(object)["id"=>"5", "name"=>"test5"]
];
var_dump($json_php_oupout);
if you want VALUE as an array to it like this adding manually indexes or with a loops.
$VALUE[0] = (object)array("id" => "1", "name" => "test1");
$VALUE[1] = (object)array("id" => "3", "name" => "test3");

Related

How i can this json data to write in php

I am sending request using curl.
this is json data :
{
"users": [
{
"userId": "123",
"userLink" : "www.example .com",
"userType": "au"
}
]
}
I am trying this but i need same above json:
$post = array(
"users" => array(
"userId" => "123",
"userLink" => "link",
"userType" => "au"
)
);
$out = array_values($post);
$post = json_encode($out);
print_r($post);
You need an additional array dimension, and if you use brackets [ ] you can easily see how they look the same:
$post = [
"users" => [
[
"userId" => "123",
"userLink" => "link",
"userType" => "au"
]
]
];
$post = json_encode($post);
Also, don't use array_values; that will remove the string key users.

Best Practice To Convert Regular Array To Associative Using An Attribute as a Key?

Let's say I have the following array
[
{
"id": "16",
"name": "dog",
},
{
"id": "17",
"name": "cat",
},
{
"id": "18",
"name": "mouse",
}
]
I want to use a specific attribute, id as the key for the array. I could do this:
$someArray = [
["id" => "16", "name" => "dog"],
["id" => "17", "name" => "cat"],
["id" => "18", "name" => "mouse"]
];
$newArray = [];
foreach ($someArray as $currItem)
{
$newArray[$currItem["id"]] = $currItem;
}
Then I would have this (the desired outcome)
{
"16": {
"id": "16",
"name": "dog"
},
"17": {
"id": "17",
"name": "cat"
},
"18": {
"id": "18",
"name": "mouse"
}
}
My question is: is there a better way to do this? Do I really have to loop through every item just to redefine my array ever so slightly?
I seem to have found a solution using information from Rizier123's comment and this thread: PHP Change Array Keys
As far as I can tell array_column is only going to give me an array of ids, so I need to use it with array_combine and array_values. Please don't be afraid to post if you have a better answer
$someArray = [
["id" => "16", "name" => "a"],
["id" => "17", "name" => "b"],
["id" => "18", "name" => "c"]
];
$newArray = array_combine(array_column($someArray, "id"), $someArray);
You beat me to the answer but I might contribute a little anyway...
I'm not sure where your original array is coming from, but if you are decoding JSON, then you can provide a second param to force objects to be converted to associative arrays
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents, TRUE); // note the second parameter
$v = array_combine(array_column($arr, "id"), $arr);
var_dump($v);
EDIT:
If you can tolerate your output array having objects, this might also work:
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents);
$v = array_combine(
array_column(
array_map(
function($item) { return (array)$item; },
$arr
),
"id"
),
$arr
);
var_dump($v);
Keep in mind though that performance could become a concern for very very large arrays. This is doing a lot of array munging.

Converting an array to replicate an associative/sequential json

I'm trying to replicate this json by converting a php array with json_encode:
"sort" : [
{ "age" : "desc" },
"_score"
]
With the following PHP array:
$json_doc['sort'] = array(
"_score",
"age"=>"desc"
);
If I just have the score in the array, PHP properly does not assign a key to the array:
"sort" : [
"_score"
]
But when I mix the "age"=>"desc" into the mix, json_encode does not encode the _score correctly:
"sort": {
"0": "_score",
"age": "desc"
}
$json_doc['sort'] = Array(
"_score",
Array('age' => 'desc')
);

Need to fetch values from Angular JS array

I am using a MVC model in PHP. I am getting the following string from the View layer (This is a angular.js array but I am getting it as a string):
[
{
"name" : "item",
"price" : "123",
"quantity" : 12,
"id" : 1
}, {
"name" : "hhh",
"price" : "000",
"quantity" : 12,
"id" : 2
}, {
"name" : "kk",
"price" : "88",
"quantity" : 12,
"id" : 3
}
]
How can I extract the values of name, price, quantity and id from this string and put that into insert query?
This is what is known as a serialized array, meaning that it is a JavaScript array in string form (JSON). You can use PHP's json_decode function to deserialize the string, from there you can use it as a normal array:
$json='[
{
"name" : "item",
"price" : "123",
"quantity" : 12,
"id" : 1
}, {
"name" : "hhh",
"price" : "000",
"quantity" : 12,
"id" : 2
}, {
"name" : "kk",
"price" : "88",
"quantity" : 12,
"id" : 3
}
]';
$array=json_decode($json);
foreach ($array as &$value) {
var_export($value->name);
var_export($value->price);
var_export($value->quantity);
var_export($value->id);
}
The above should display all the values in your array. I'm not sure what you mean by "put that into the insert query", but hopefully the above will help you get access to this data.

Accessing JSON encoded PHP Array in jQuery

I have an PHP Array which is formatted in the following format :
$jsonArray = array(
"facebook" => array("user" => "8", "user_id" => "10", "user_post" => "6"),
"twitter" => array("user" => "8", "user_id" => "10", "user_post" => "6")
);
I've then done the following so I can access the array
echo "<script type='text/javascript'>window.MyArray = ".json_encode($jsonArray).";</script>";
And to access the array I tried the following
alert(window.MyArray['facebook'][0]['user']);
yet that's seemed to fail, any directions?
window.MyArray['facebook'][0]['user']
--------------------------^^^
Why do you need [0] here?
Use this:
window.MyArray['facebook']['user']
MyArray gives this:
{
"facebook": {
"user": "8",
"user_id": "10",
"user_post": "6"
},
"twitter": {
...
}
}
MyArray['facebook'] results in the following array:
{
"user": "8",
"user_id": "10",
"user_post": "6"
}
Therefore, MyArray['facebook']['user'] results in 8.
try this way:
alert(window.MyArray.facebook.user);
it will work
You are passing the json as a string, you need to convert it to an object. To do that you can use http://www.json.org/js.html

Categories