I know there are a lot of similar question as this one on here but the problem I keep running into is that the method in which those other json file arrays are setup is not the same as mine.
What I am trying to do should just be a simple process but as I am not as versed in json arrays and I am other things, the solution is eluding me completely.
I just want to take the data display in a local json file and create PHP variables for each item returned.
The json file is simple and looks something like this...
[
{
"titleOne": "Foo",
"textOne": "Bar",
"titleTwo": "Foo",
"textTwo": "Bar"
}
]
It will always consist of just these 4 items. Then I use the following PHP to read and decode the file...
$data = file_get_contents ('./data.json');
$json = json_decode($data, true);
foreach ($json as $key => $value) {
foreach ($value as $key => $val) {
echo $key . '====>' . $val . '<br/>';
}
}
but this simply outputs the data. I am trying to get each one of these 4 items to become variables. Example...
$titleOne
$textOne
$titleTwo
$textTwo
...so that the variables can be used in a form.
I have found many similar questions as this but the json data is always setup differently resulting in errors as results.
Why not simply define if it's always only 4:
$titleOne = $json[0]['titleOne'];
$textOne = $json[0]['textOne'];
$titleTwo = $json[0]['titleTwo'];
$textTwo = $json[0]['textTwo'];
You can use list to extract elements into variables. Keep in mind, that it only works with numerical arrays.
$json = '[
{
"titleOne": "Foo",
"textOne": "Bar",
"titleTwo": "Foo",
"textTwo": "Bar"
}
]';
$json = json_decode($json, true);
foreach ($json as $object) {
list($titleOne, $textOne, $titleTwo, $textTwo) = array_values($object);
}
With php you can't use a variable to name another variable. You could however use an associative array to do this.
The true in json_decode($data, true); already returns the data in the form of an associative array. In order to access the value of titleOne, you would just do $json['titleOne']. This would give you Foo.
With php you CAN use a variable to name another variable.
Just use Variable variables :
$a = 'var';
$$a = 'hello world';
echo $var;
// output : hello word
In your case :
You don't have to wrap your json data in array and make 2 loops :
{
"titleOne": "Foo",
"textOne": "Bar",
"titleTwo": "Foo",
"textTwo": "Bar"
}
You can create your dynamic variables this way :
$data = file_get_contents ('./data.json');
$json = json_decode($data, true);
foreach ($json as $key => $val) {
$$key = $val;
}
echo $titleOne;
// output : Foo
Related
I have a variable in PHP, named as $partialSegments. I want to iterate through it and perform actions when I strike operator or rOperandValue, etc. I receive it in a function call, so while making the
function named(say):
public function convertJsCode($partialSegments){
//logic
}
I am struggling with the logic
"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}
Use json_decode() function in php
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed["segments"]["partialSegments"] as $val) {
$operator = $val["operator"]; // operator value
$rOperandValue = $val["rOperandValue"][0]; // rOperandValue value
}
?>
Step1: convert json encoded data into php array using json_decode(); function. This function receive two arguments: first one is: json_encoded data which should be decoded and 2nd one is: boolean(TRUE or FALSE). pass second argument as TRUE to convert the json concoded values as php array, if you pass false it will return php object.
Step2: iterate php array and set the logic like a charm.
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed as $single){
$segments = $single['partialSegments'];
//print_r($single);
foreach($segments as $segment){
echo 'operator:'. $segment['operator'].'<br>';
print_r($segment['rOperandValue']);
// put your logic based on 'operator' or 'rOperandValue'
}
}
?>
Suggestion: Don't use hard code index to work with an array like: $segment['rOperandValue'][0]. array could be empty. i.e: if you want to do anything when a value is found in $segment['rOperandValue'] use in_array().
I'm new to PHP and web programming at all.I am trying to read some json data from steam API.
Data: http://pastebin.com/hVWyLrfZ
I managed to get to single objects(I believe?).
This is my code:
<?php
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$heroes = reset(reset($data));
//var_dump($heroes);
$wat = reset($heroes);
$antimage = array_values($heroes)[0];
var_dump($antimage);
?>
I want data to be in array like this:
id => name
I mean, array keys should be ids and values should be hero names.
Also,the where I set heroes variable to reset(reset($data)) seems like a bad way of doing what I want, maybe there are better ways?
You can use array_map() function to extract both id and names in two separate arrays and then use array_combine() to create a key-value pair array from the previously extracted arrays.
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);
$ids = array_map(function($a) {
return $a['id'];
}, $data['result']['heroes']);
$names = array_map(function($a) {
return $a['name'];
}, $data['result']['heroes']);
$heroes = array_combine($ids, $names);
print_r($heroes);
A simpler more obvious solution is to simply loop thru it. From your pastebin, I see that your data is wrapped in two levels of array so ...
$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
$myResult[$nameId['id']] = $nameId['name'];
}
(No need to do any reset calls; that's a weird way to get the first element of an array)
Note, for this to work, you must apply the tip by #RamRaider
$data = json_decode($JSON, true);
in order for json_decode to return arrays, not StdClass.
I have some issue with a decoded Json object sended to a php file. I have tried some different format like this
{"2":"{Costo=13, ID=9, Durata_m=25, Descrizione=Servizio 9}","1":"{Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}"}
or this.
[{"Costo":"7.5","ID":"3","Durata_m":"30","Descrizione":"Barba Rasoio"},{"Costo":"4.5","ID":"4","Durata_m":"20","Descrizione":"Barba Macchinetta"}]
In order the first, any suggestions helps me, then i have converted previous string using GSON, however php doesn't decode.
This is my php:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data['servizi'] as $key => $value)
{ echo "Key: $key; Value: $value<br />\n";
}
How can I access single elements of array? What I'm doing wrong? Thanks in advance
I think you should check the content in this way
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
echo "FROM PHP: " . $value;
echo "Test : " .$value['ID'];
}
your elements of {Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}
are not properly formated as an array element. That is a pure string and not an array value.
This is a json object with 1 element of array:
{
"1": {
"Costo": 7,
"ID": 8,
"Durata_m": 20
}
}
The Inside are json objects. Therefore your json string was not properly formated to operate with that logic. What you had was an element of a string. That is the reason why it was a valid json (passing jsonlint) but was not the correct one that you wanted to use.
UPDATE
Because this format is fix, I have a non-elegant way:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
//to separate each element
$newArray = explode(',',$value);
$newItem = explode('=', $newArray[1]);
echo "ID". $newItem[1];
}
That would be the dirty way to do it ONLY IF THE PLACEMENT OF DATA IS FIX. (ie the second element of the first explode is always ID.
I will leave it to someone else to make the suggested code better. I would recommend more to ensure that the json you are receive is proper because as I explained, it is incorrectly formated and as an api developer, you want an adaptive way for any given client to use the data efficiently.
Excuse me if this has been covered, but I've looked and can't find an answer that works.
I have the following JSON (shortened for clarity):
[{
"header": {
"msg_type": "0001"
},
"body": {
"event_type": "ARRIVAL",
"train_id": "384T22MJ20"
}
},{
"header": {
"msg_type": "0003"
},
"body": {
"event_type": "DEPARTURE",
"train_id": "382W22MJ19"
}
}]
Now I know I can use json_decode to create a php array, but not knowing much about php I don't know how to get it to do what I want. I need to be able to access a value from each array. For example I would need to extract the train_id from each array. At the moment I have this:
$file = "sampleData.json";
$source = file_get_contents($file);
$data = json_decode($source);
$msgbdy = $data->body;
foreach($msgbdy as $body){
$trainID = $body->train_id;
}
I know this is wrong, but I'm not sure if I'm on the right track or not.
Thanks in advance.
anonymous objects are deserialized as array-members, foreach can handle that :
$objs = json_decode($source)
foreach($objs as $obj)
{
$body = $obj->body; //this is another object!
$header = $obj->header; //yet another object!
}
and within that loop, you can now access msg_type, train_id and event_type via $body and $header
I suggest to pass it true as a parameter, it is easier to work with associative arrays than objects:
$messages = json_decode($source, true);
foreach($messages as $message){
$trainID = $message["body"]["train_id"];
}
You process it in the wrong order: your string is an array of objects. Not an object with arrays.
You first need the large foreach loop to iterate over the array and then access for each element the "body" and "train_id".
Your code should thus read:
foreach($data as $item) {
echo $item->body->train_id; //or do something else with $item->body->train_id
}
Maybe something like:
$data = json_decode($source);
foreach ($data as $message) {
$trainId = $message->body->train_id;
// Not sure what you want to do wit this ^
}
You need to loop over each whole entry. See how where the data is repeated, and that is what you need to loop over.
Your trying to access an array like an object. The array notation would be $data[0]['body'] to retrieve the value for the "body" key in the first entry in the array.
I'd appreciate any help I could get with this — I've been scouring stack overflow and couldn't find anything that directly related with what I'm trying to accomplish.
Issue: I'm trying to update a specific name/value pair in a JSON file, and I'm trying to do it by sending specific parameters through an AJAX call to a PHP file. Two of the parameters are the path (delineated with hyphens) to the name, and the value that I'm swapping in.
A small portion of the JSON:
{
"character" :
{
"name" : "Foo",
"species" : "Bar",
}
}
Using this JSON as an example, I'm trying to update a specific array value, such as:
$char['character']['name']
I'm passing a variable to the PHP file with the path information, such as:
updater.php?char=character-name&val=Newname
Is there a way to convert the string "character-name" (or any string for that matter with a particular delineation) to the path in an Array, like $char['character']['name']?
$array = explode("-", $_GET['char']);
$char=json_decode(....); //your json string
$char[$array[0]][$array[1]]=$_GET['val'];
To not only read the value at the specified path, but also update the json, I would suggest something like
<?php
function json_replace_path($json, $path, $newValue)
{
$json = json_decode($json);
$pathArray = explode('-', $path);
$currentElement = $json;
foreach ($pathArray as $part)
{
$currentElement = &$currentElement->$part;
}
$currentElement = $newValue;
return json_encode($json);
}
$json = '{"character":{"name":"Foo","species":"Bar","other":{"first_name":"Jeff","last_name":"Atwood"}}}';
echo json_replace_path($json, 'character-name', 'new name') . "\n";
echo json_replace_path($json, 'character-species', 'new species') . "\n";
echo json_replace_path($json, 'character-other-last_name', 'Bridges') . "\n";
Does not support JSON including arrays, though.
Something like that should work, I guess :
$a = explode("-", $_GET['char']);
$array = ...; //Your json array here
while (is_array($array) && count($a) > 0)
{
$array = $array[array_shift($a)];
}
Why not just use updater.php?character[name]=Newname? Then you can get it with:
echo $_GET['character']['name'];
Makes much more sense. Why concatenate things and then try and separate them into an array when you can just use an array from the start?