converting a delineated string into an array path in PHP - php

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?

Related

How to read json encoded value using php?

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().

Returning Json Data To PHP Variables

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

JSON decode Array and insert in DB

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.

php issue accessing array

I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
}
This is the output :
["SOUL MINORITY"]
["INLAND KNIGHTS"]
["DUKY","LOQUACE"]
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Thanks
UPDATE :
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also.
There must be some processing done in the back.
Any idea how I can extract the information, for example from :
["DUKY","LOQUACE"]
to get :
DUKY, LOQUACE
Thanks for your time
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
var_dump($r['trackArtist']);
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.

How to deserialize this string into a PHP array of key => value pairs?

I'm calling the script at: http://phat-reaction.com/googlefonts.php?format=php
And I need to convert the results into a PHP array format like the one I'm currently hard coding:
$googleFonts = array(
"" => "None",
"Abel"=>"Abel",
"Abril+Fatface"=>"Abril Fatface",
"Aclonica"=>"Aclonica",
etc...
);
The php returned is serialized:
a:320:{
i:0;
a:3:{
s:11:"font-family";
s:32:"font-family: 'Abel', sans-serif;";
s:9:"font-name";
s:4:"Abel";
s:8:"css-name";
s:4:"Abel";
}
i:1;
a:3:{
s:11:"font-family";
s:38:"font-family: 'Abril Fatface', cursive;";
s:9:"font-name";
s:13:"Abril Fatface";
s:8:"css-name";
s:13:"Abril+Fatface";
}
etc...
How can I translate that into my array?
You can do this by unserializing the data (using unserialize()) and then iterating through it:
$fonts = array();
$contents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$arr = unserialize($contents);
foreach($arr as $font)
{
$fonts[$font['css-name']] = $font['font-name'];
}
Depending on what you're using this for, it may be a good idea to cache the results so you're not fetching external data each time the script runs.
Use unserialize(): http://www.php.net/unserialize

Categories