I want to add comment on facebook post.. via facebook API
The function that adds the comment is
public function fill($json)
{
if(isset($json['data']))
{
$json = $json['data'];
}
foreach($json as $k => $v ) $this->{$k} = $v;
}
I am passing the data in json format as
{"data":{"id":"153870348034313_347443752010304","message":"test comment"}}
but the response is: Invalid argument supplied for foreach()
You didn't decode the JSON:
public function fill($json)
{
$json = json_decode($json);
if(isset($json->data))
{
$json = $json->data;
}
foreach($json as $k => $v ) $this->{$k} = $v;
}
Related
Greeting, I'm new to PHP, and currently looking for a way to edit json.
I have a form to input the key that wants to edit. I echo the input from form and successfully got the output showing but it didn't pass to json file to update. The code is as below.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = json_decode($data, true);
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
//you this post contain test?
//test is the the button when i submit the form
if (array_key_exists('test',$_POST))
{
testfun();
}
Am I missing something?
Try my code.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = array(json_decode($data, true));
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
if (array_key_exists('test',$_POST))
{
testfun();
}
As you mention in the comments, the content of the $json_arr is:
{"CELL_NAME":"1234A","#25":"remark value"}
So when you trying to access in:
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
it has no key for $value at CELL_NAME key.
I guess your $data from the file should be like that (an array of JSONs):
$data = '[{"CELL_NAME":"1234A","#25":"remark value"}, {"CELL_NAME":"1234B","#25":"remark value"}]';
Now you can do this and it will work:
$arr = json_decode($data, true);
foreach ($arr as $key => $value) {
if ($value['CELL_NAME'] == "1234A") // you can change with $_POST['in_cell']
$arr[$key]['#25'] = "test"; // you can change with $_POST['in_remark']
}
I'm trying to parse JSON data in the format [{code:SE rate:1.294},{code:UK rate:2.353}] from this page:
http://www.mycurrency.net/service/rates
I have implemented an IP reader that detects the users location in a 2 letter country code. I want to pluck the correct data from that link with 'code' and return the value 'rate'. I was thinking I might have to do a foreach loop to iterate through all the countries?
This is my code, I hope this is what are you looking for.
First I create a new array $output to make it more easy to search
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
After that we use a function to search value in array and returning the key. I got it from here
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
and then I run the function with the first parameter as country code to get the keys of specific country code.
$find = searchForRate("BT", $output);
And then echo the rates from our $output array by key in $find variable
echo 'RATE = '.$output[$find]['rate'];
This is the complete codes
<?php
$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);
foreach ($json as $key => $data) {
$output[$key]['code'] = $data['code'];
$output[$key]['rate'] = $data['rate'];
}
function searchForRate($countryCode, $array) {
foreach ($array as $key => $val) {
if ($val['code'] === $countryCode) {
return $key;
}
}
return null;
}
$find = searchForRate("BT", $output);
echo 'RATE = '.$output[$find]['rate'];
Example output:
RATE = 64.13
I have json string that I have to edit and then transform back to json. But unfortunately I can't really restore the json structure.
The structure of the original json string ($json):
"[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
The structure I get after my edits ($newJson):
"{"0":{"Language":{"0":"EN"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"1":{"Language":{"0":"DE"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"2":{"Language":{"0":"FR"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}}}"
Here is what I do with my edits:
$jsonArray = object_to_array(json_decode($json));
$editedJsonArray = someLoopStuff($jsonArray);
$newJson = json_encode(array_to_object(($editedJsonArray)));
function object_to_array($obj) {
if(is_object($obj)) $obj = (array) $obj;
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = $this->object_to_array($val);
}
}
else $new = $obj;
return $new;
}
function array_to_object($a) {
if (is_array($a) ) {
foreach($a as $k => $v) {
$a[$k] = $this->array_to_object($v);
}
return (object) $a;
}
return $a;
}
Do you have an idea how I could get the same structure as the original json?
Use arrays instead of objects. Pass true to json_decode() as second argument and then do your stuff on arrays.
$jsonArray = json_decode($json, true);
Then just make your operation in loop on $jsonArray and simply use json_encode() without any additional work.
To achieve exactly same output as you have on input you need to cast subarrays on objects:
$jsonArray = json_decode('[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]', true);
foreach ($jsonArray as &$item) {
foreach ($item as &$val) {
$val = (object) $val;
}
unset($val);
}
unset($item);
var_dump(json_encode($jsonArray));
Output:
string(226) "[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
What if you would try to avoid using functions object_to_array and array_to_object. In the encoding part it is not necessary, because json_encode can handle objects or arrays. In the first part json_decode can be called with second optional parameter set to true to produce array instead of object. See PHP manual.
Is there a way to retreive a key from JSON string with out going in to foreach loop?
$json ="{\"error\":{\"code\":301}}";
if (empty($json)) {
die('empty string');
} else {
$obj = json_decode($json);
foreach ($obj as $key => $object) {
echo $key;
}
}
What I need is to detect where the string contains error or not, so I can create error handling.
Thanks in advance
You can use property_exists() method:
$json ="{\"error\":{\"code\":301}}";
if (empty($json)) {
die('empty string');
} else {
$obj = json_decode($json);
var_dump(property_exists($obj, 'error'));
}
[{"name":"se","value":"test1"},{"name":"model","value":"test2"},{"name":"filter_preference","value":"test3"},{"name":"seved","value":"test4"}]
I have json, and I would like to parse it, and to get for "segment" => "test1"
and so on.
i have done this
$json2= json_encode($loadFilter);
$json2 = json_decode($json2, true);
foreach ($json2->$key as $value)
{
echo $key ."=>".$value;
}
always getting Invalid argument supplied for foreach() !!!
I am doing it WP ajax callback.
Your foreach syntax is wrong to access the $key.
foreach ($json2 as $key => $value) {
echo $key ."=>".$value;
}
Edit from your comments:
You didn't give the "real" format in your question, your array is contained in 'filter_preference', so you have to iterate over $json2['filter_preference'].
foreach ($json2['filter_preference'] as $key => $value) {
echo $key ."=>".$value;
}
you need to map key value for sub array.
try this:
foreach ($json2 as $key=>$value)
{
echo $key ."=>".$value;
}
One odd suggestion here:
If you want to use array for this then you can convert object to array using following code:
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
$array_new = objectToArray($json2);
http://wonderphp.wordpress.com/2014/03/20/convert-object-to-array-and-vice-versa/