Merging to array and getting error - php

Here is what i am doing, Storing values from a form to array and then storing that array into a file (array.jason).
if (isset($_POST['addEntity'])) {
$values = array_values($_POST);
print_r($values);
unset($values[1]);
var_dump($values);
$file_values = json_decode(file_get_contents('array.json'), true);
array_combine($file_values,$values);
file_put_contents("array.json",json_encode($values),FILE_APPEND);
}
Now, when i try to merge array from file ($file_values) to an array which i get from submit ($values) i am getting this error or warning :(
Warning: array_combine() expects parameter 1 to be array, null given
in C:\Users\tej\PhpstormProjects\Final Year Project\index.php on
line 9

So there are a few things wrong in your code which got you a few errors. First I will show you how you can fix your code and second what went wrong and what happened.
So to fix your code you have to assign the return value of array_combine() back to $values and just overwrite the file, since you added the new data to the old decoded one, e.g.
if (isset($_POST['addEntity'])) {
$values = array_values($_POST);
unset($values[1]);
$file_values = json_decode(file_get_contents('array.json'), true);
$values = array_combine($file_values,$values);
file_put_contents("array.json", json_encode($values));
}
But what happened without that assignment and the appending of the file is. You just encoded your new data into JSON and appended it to your file. Means you created:
[DATA 1]
[DATA 2]
[DATA ...]
So when you tried to decode it again, all encoded data combined weren't valid anymore, even though they are as a single line they aren't as entire file. Which then lead json_decode() return NULL, since it wasn't valid JSON, and finally you tried to combine NULL with an array which got you a PHP error.

Related

Read nested json in php

I know others have already asked about this, but I don't find a solution for my problem. In my PHP page I call an external service and I can't modify the response obtained.
I'm moving my first steps both with JSON and PHP.
The response is a JSON like this, I print this using the var_dump method:
object(stdClass)#1 (3)
{
["search_string"]=>string(15) "ABCDEFG HI LMNO"
["resut"]=>string(5) "apixi"
["0"]=>array(1){
[0]=>object(stdClass)#2(2){
["resp_code"]=>string(7) "12.34.0"
["resp_description"]=>string(15) "ABCDEFG HI LMNO"
}
}
}
In my PHP page I can read the value ”ABCDEFG HI LMNO” for the key "search_string" with this code, in the $output variable I store the result of the cUrl call
.......
$output = curl_exec($ch);
$jsonDecode =json_decode(str_replace('""','"',$output));
var_dump($jsonDecode);
echo $jsonDecode -> search_string;
I need the str_replace method because the JSON is dirty but not always, how can I access at the fields "resp_code" and "resp_description" and then store them in a variable? I tried many solutions but none works for me.
Instead of converting JSON array to stdClass object you can also convert it to regular PHP array by adding second parameter to the json_decode function:
$jsonDecode =json_decode(str_replace('""','"',$output), true);
In your case in the output, you'll get a multidimensional array.
Then, to access resp_code and resp_description, you can do something like this:
$respCode = $jsonDecode[0]["resp_code"];
$respDescription = $jsonDecode[0]["resp_description"];
In the decoded JSON you have, the resp_code and resp_description keys are difficult to get to, because the top-level object has a numerical ("0") attribute. Trying to reach that attribute like this:
$jsonDecode -> 0
will give this parsing error:
syntax error, unexpected '0' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
Trying the same with a string notation (-> "0") also fails.
However, the suggestion in the error message is useful: encapsulate the zero with braces. Then you can proceed easily by adding the array index selector ([0]) to get to the object and keys of your interest, like this:
echo $jsonDecode->{0}[0]->resp_code;
echo $jsonDecode->{0}[0]->resp_description;
If you expect more elements in that array $jsonDecode->{0}, then loop over them like this:
foreach ($jsonDecode->{0} as $element) {
echo $element->resp_code;
echo $element->resp_description;
}
Alternative
If, however, you prefer to work with associative arrays instead of objects, you can use the second argument of json_encode as stated in the docs:
assoc
When TRUE, returned objects will be converted into associative arrays.
So then you would pass true as second argument:
$jsonDecode = json_decode(str_replace('""', '"', $output), true);
The above code would then be rewritten like this to access the variable as an associative array:
foreach ($jsonDecode[0] as $element) {
echo $element["resp_code"];
echo $element["resp_description"];
}

json_decode() getting values

I am trying to get json data from the Statcounter API.
I have the following:
$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];
I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.
Here are the first couple lines of the unformatted json it is giving me.
This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.
http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514
{"#attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar
Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!
Thank you for your help.
Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:
echo $data['sc_data'][0]['log_visits'];
The code above will access the first element of the array sc_data and print the value of log_visits
When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].
The elements of the array can be any valid value, i.e.
string
number
object
array
true
false
null
In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")

Looping through json_decode with foreach loop error

I keep running into the error Warning: Invalid argument supplied for foreach() and for the life of me I can't figure out why. Here is my relevant code:
$Ids = $_POST["param-0"];
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
stripslashes($decodedJson);
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
$Ids is a string from a previous file that is encoded with json_encode. I added the stripslashes because it was recommended in another question on Stack Overflow, but it didn't help. If I change the beginning of the foreach loop to beforeach($toReturn as $id) the error goes away. Thanks!
edit: in the previous file, $_POST["param-0"] is an integer array that I returned with json_encode. With the testing data I am working with right now, ["15","18"] is what is being passed.
First you need to decode the json (which you already did)
$decodedJson = json_decode($Ids, True);
Then to grab each value from the json and, for example, echo it. Do this:
foreach ($decodedJson as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $value) {
echo $value; // This will show jsut the value f each key like "var1" will print 9
// And then goes print 16,16,8 ...
}
}
From top to botton:
$Ids = $_POST["param-0"];
This will trigger a notice if input data does not have the exact format you expect. You should test whether the key exists, for instance with isset().
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
This will return null if input data is not valid JSON. You should verify it with e.g. is_null().
stripslashes($decodedJson);
If input data was valid we'll first get a warning:
Warning: stripslashes() expects parameter 1 to be string, array given
Then, if our PHP version is very old we'll have our array cast to a string with the word Array in it, and if our PHP version is recent we'll get null. Whatever, our data is gone.
If input data wasn't valid, we'll get an empty string.
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
Neither null or strings (empty or not) are iterable. There's no nothing to do here. Our data is gone forever :_(
It ended up I was incorrectly encoding what I wanted decoded. All is well again, thanks for everyone's help!

Can't get value from array

I'm trying to output the value of the email value of an array, but have problems doing so.
The array is based on json_decode()
This is the error I receive
Fatal error: Cannot use object of type stdClass as array in /home/.... line 57
JSON (value of: $this->bck_content)
{"email":"test#email.com","membership_id":"0","fname":"Kenneth","lname":"Poulsen","userlevel":"1","created":"2012-04-23 10:57:45","lastlogin":"2012-04-23 10:58:52","active":"y"}
My code
# Display requested user details
$details_array = json_decode($this->bck_content);
$value = $details_array['email'];
print $value;
You need to use the second argument to json_decode to force array structures on JS objects.
json_decode($this->bck_content, true);
This will make sure all JS objects in the json are decoded as associative arrays instead of PHP StdObjects.
Of course that is assuming you want to use array notation to access them. If you're fine with using object notation then you can just use:
$value = $details_array->email;
try this one
$value = $details_array->email;
or
json_decode($json, true);
or
$details_array = (array)json_decode($json);
what have you done wrong is writen in error description

Unable to un-serialize an array of arrays with PHP

The array in the database is stored as a serialized string, such as this:
a:1:{i:0;a:4:{s:8:"category";s:26:"Category Name";s:4:"date";s:0:"";s:8:"citation";s:617:"617 Char Length String (shortened on purpose)";s:4:"link";s:0:"";}}
It's structure should resemble the following when unseralized:
array {
id => array { category => Value, date => Value, citation => Value, link => Value }
}
The php code I'm using is:
$prevPubs = unserialize($result[0]['citations']);
The $result[0]['citations'] is the serialized string. $prevPubs will return false. Which indicates an error if I'm not mistaken.
Any help would be greatly appreciated.
b:0 is boolean:false in serialized format. Unserialize would NOT return that exact string, it'd just return an actual boolean FALSE. This means that whatever you're passing into the unserialize call is not a valid serialized string. Most likely it's been corrupted somehow, causing the unserialize call to fail.
in order to handle serialized multidmensional arrays and mysql use this:
<?php
//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));
//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));
?>
i'm pretty sure serialized string in your database is corrupted
You have to unserialize the whole string
$result = unserialize($serialized);
and then use the $result[0]['citation'] index of the result array.

Categories