JSON encode_decode weird behave PHP - php

I have array input in HTML Form as below
<select name="age[]" id="ageFrom">..Age Options..</select>
<select name="age[]" id="ageTo">..Age Options..</select>
Upon submission, I am saving data in mysql database as json_encoded value like ["20","25"]
foreach($request->request as $key => $value) {
ProfileSettings::create([
'uid' => $curMID,
'code' => 'preference',
'key' => $key,
'value' => json_encode($value),
'serialized' => 1
]);
});
Now, when it get this value from DB and try to decode it as
$val = json_decode(["20", "25"]) OR json_decode(["20", "25"], true)
My DB returns value like
Then i get an error like
htmlspecialchars() expects parameter 1 to be string, array given
Kindly help me to get 20 and 25 as $val[0] and $val[1]

Thing is, you're calling json_decode on a php array [ ].
It expects a string, which it'll convert to an array.
Perhaps you wanted to use json_encode instead? If so, change your code to:
$val = json_encode(["20", "25"]) OR json_encode(["20", "25"], true)

The problem is that the value coming from the data base is ["20", "25"] and when is inserted in the json_decode() function is interpreted as an array.
To solve the problem insert the value in between double quotes.
$val = json_decode("$result") or $val = json_decode('["20", "25"]')

Related

How to get each value of unserialized data

Lets say I have this data...just an example!
Before Serialize
array (size=2)
'first_name' => string 'Swashata'
'last_name' => string 'Ghosh'
After Serialize
a:2:{s:10:"first_name";s:8:"Swashata";s:9:"last_name";s:5:"Ghosh";}
So after the serialized data I'm going to unserialized it and get each value of the element of array to make it variable. The problem here is I want to get each element to make them a variable so that I can easily call them when I need it. Thanks! ahead.
I think you ask for extraction of key => value to variables..
So ..
$array = array(
'first_name' => 'Swashata'
'last_name' => 'Ghosh'
);
extract($array);
This will create variables called $first_name and $last_name with their values from your array..
After unserialize you need to call
$unserialized = unserialize($data);
echo $unserialized['last_name'];
not $unserialized[0]
You can use this as well
extract($unserialized);
echo $last_name;
Hope this is helpful.
Its in json format
Use json_decode() to get the values from serialized data
$a = "serialized data";
$arr = json_decode($a);
print_r($arr);// will get back the result

how to decode the encoded array value

I want to decode the array value in web service.I need to decode 'CONTENT_VALUES' field which has name and value as its object and pass it in json.ID and USER_ID return correct value(separate field) but name and question returns null. I want to decode 'ques' => $datas->name, 'answer' => $datas->value.value of CONTENT_VALUES=[{"name":"radio","value":"","sur_id":"3","user_id":"admin#gmail.com","pagename":"question_response"},{"name":"true","value":""}]
$query1 = mysql_query("select * from `$prefix.response` where ID='$sur_id'");
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
$datas = json_decode($content);
$test[] = array('ID' => $fetch['ID'], 'USERID' => $fetch['USER_ID'], 'ques' => $datas->name, 'answer' => $datas->value);
}
Take a look at http://php.net/manual/en/function.json-decode.php.
This will describe how to convert a JSON string into a PHP object or array.
When you get stuck more with this you can fairly simple google "php decode json" and find plenty helpful resources.
Edit: Read the question too quick just before and understood it wrong, have you tried checking the return result of your $datas = json_decode($content) statement? Does CONTENT_VALUES actually contain JSON encoded data? Does the decoded object actually contain name and value?
May be you should set use mb_convert_encoding before decoding like this
$content = $fetch['CONTENT_VALUES'];
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content_value);

How to pass array in laravel where condition?

$table='user';
$conditions=array(
'uname' => 'test',
'pwd' => '123'); //uname and pwd are the column names
DB::table($table)->where($conditions)->get();
while excuting above code its showing following error
ErrorException
strtolower() expects parameter 1 to be string, array given
Can any one help me pls.
I don't know which classes you are using but your php compilator said that you passed array instead of string, so maybe try pass conditions in string format:
$conditions = "uname='test'&pwd='123'";
UPDATE
As you can see in docs (http://laravel.com/docs/queries#selects), you can only pass strings to where method so you have to do sth like that:
$select = DB::table($table);
foreach($conditions as $column=>$value){
$select->where($column,'=',$value);
}
$result = $select->get();

Get JSON data type from associative array in PHP

Evening everyone!
So, I have with me a JSON string...
{"username":"87db3983285d395ca0af9f","password":"f4f0bb1533ef5034ce6b0a8a7c49a43b","email":"xxx#gmail.com","hnum":3,"splicenum":22,"reg_ip":"71.126.122.217","reg_date":1364175245,"cur_ip":"71.126.122.217","ip_array":["71.126.122.217"],"logins":[],"about":""}
And I decode this string into an associative array in PHP using json_decode().
What I'm doing is trying to make 1 single function for querying a JSON object that has been converted to an associative array in PHP. For this function, I am now working on editing/updating fields.
Example:
json_edit(array(
"set"=>array(
"email"=>"yyy#yahoo.com"
)
));
The key "set" means setting the value of a string or boolean.
Another key would be "push" to append to an array, or "delete" to delete a string or an array.
What I'm wondering is, how can I get the data type of the current array part in PHP?
Meaning, how can I get PHP to say, "OK, the field 'username' is a string, and 'ip_array' is an array"?
I don't want to be able to "set" a string value to what is SUPPOSED to be just a boolean, or, an array.
Is there any way to get the JSON data types in PHP?
Thanks so much in advance.
What about gettype(). Gettype() will return the data type of any variable. http://php.net/manual/en/function.gettype.php
I would use something like this;
<?php
function json_edit($json, $changes = array()){
$decoded = json_decode($json);
foreach($changes as $action => $data){
swith($action){
case 'SET':
foreach($data as $key => $value){
$decoded[$key] = $value;
}
break;
case 'DELETE' :
break;
default;
}
}
return json_encode($decoded);
}
?>

What kind of php array is this and how do I edit it?

I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));

Categories