I am trying to convert this JSON string into a PHP array. The JSON string is stored in my database and I have already retrieved it.
{
"users": "user1, user2"
}
I need to convert the above JSON string into an array like the following but dynamically.
$myArray = array("user1", "user2")
This is my code:
$row = mysqli_fetch_array($result);
$json = $row['json'];
$decode = json_decode($json);
$list = $decode->users;
$myArray = explode(',', $list);
This code doesn't work in my program but when I print the array with print_r it looks identical to if I print $myArray from the nondynamic string. This is a concern because the nondynamic string works.
The separator between the usernames is comma+space, you're just using comma when you explode, so the second and following usernames are getting a space at the beginning. Try:
$myArray = explode(', ', $list);
I recommend that you change the JSON structure so you store an actual array, rather than a comma-separated list.
{
"users": ["user1", "user2"]
}
Even better would be to change your database structure so the users are in a real table, rather than being wrapped in JSON. This would allow you to perform queries that search for users easily and efficiently.
Related
I am trying to create JSON from a comma delimited string.Now my code is like this
$sql="select Pri_name from nri_privilege";
$getvalue=mysqli_query($mysqli,$sql);
while($result=mysqli_fetch_assoc($getvalue))
{
$getallresults[]=$result;
}
foreach($getallresults as $rereult)
{
print_r($rereult);
name =$rereult['Pri_name'];
name .=$name .',';
//echo $name;
//echo json_encode($name);
}
I am fetching data from database and loop it inside a foreach. How to create JSON from a comma delimited string?
Based on the title of your post this would do what you described.
$array = ["foo", "bar", "bat"]; //some array form e.g. db
$glued = implode(",", $array); //implode it with ,
$json = json_encode($glued); //and json encode it
What I think you really want is this:
$array = ["foo", "bar", "bat"]; //some array form e.g. db
$json = json_encode($array); //json encode the array without step 2.
Guess you want to send the json encoded array over the wire to somewhere else. In this case no need for any implode or explode.
Try This
$sql="select Pri_name from nri_privilege";
$getvalue=mysqli_query($mysqli,$sql);
while($result=mysqli_fetch_assoc($getvalue))
{
$getallresults[]=$result['Pri_name'];
}
echo json_encode($getallresults);
You better not append , manually. Try this,
$names = array();
foreach($getallresults as $rereult){
$names[] = $rereult['Pri_name'];
}
then,
$comma_seperated_list = implode(", ", names);
If you want the above string to be json encoded,
json_encode($comma_seperated_list);
Otherwise you could encode the whole name array like,
json_encode($names);
Hope this helps you!
Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode
I am trying to get mysql data in to json using php and later access it in url. I am getting data in json but i need in a format. Below is my php code to get json.
header('Content-Type: application/json');
include('dbhconfig.inc.php');
$response = array();
$stmt = $dbh->prepare("SELECT * FROM venderlist");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
{
$response['results'] = $rows;
}
echo json_encode($response);
And my json data showing as bellow
{"results":[{"id":"1","vendname":"Genie Events","address":"15, Lower Ground Floor, Lajpat Nagar, Delhi - 110024, Near National Park ","contact":"(91)-11-33437065","contact_o":"(91)-11-40666522","est":"2010","website":"www.genieevents.com","email":"","zip":"110024","latitude":"1.28525","longitude":"103.775464","latlon":"1.28525,103.775464","type":"organisers"},
First of all its not showing in proper structure. And presently latlon is showing like "latlon":"1.28525,103.775464" but i want result should be "latlon":[1.28525,103.775464]
How to add [] to my json variable name latlon.
If course, you'll need to break down that part of the data first since its a string. You'll need to set them up as an array unit with both float values inside.
After fetching them all, you'll need to make a little bit of operations.
You can use explode on that string first with that ,. So that becomes an array []. But it doesn't end there, the exploded elements are still strings, so you can map out all elements with floatval with the use of arrray_map.
So all in all, it would look just like this:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as &$r) { // with reference
// explode with comma, map with floatval
$r['latlon'] = array_map('floatval', explode(',', $r['latlon']));
}
echo json_encode(array('results' => $rows)); // json encode
I want to store short arrays in a field. (I realize there are reasons to break the array up into items and store separately, but I'm opting for a simple storage option at the expense of less capability.)
My code to create the array is as follows:
$str = "one,two,three,four";
$array = explode (",",$str)
I then store into a text field in mysql using an insert statement It seems to store fine. In PhPAdmin, it shows ARRAY in the field and if I just echo $array, it prints "ARRAY".
The problem is occurring when I try to retrieve data.
I am retrieving using
while($row = mysql_fetch_array($res)) {
$array = $row['list']; //that's the field it is stored in
echo $array; // echoes "ARRAY"
//so far so good. However, when I then try to print out the contents of the array, I get error messages. I have tried using implode and also for each.
$text = implode(",", $array);//yields error message improper argument in implode function
foreach($array as $val) {
echo $val;
} //yields error message improper argument for for each statement
}
Could my entry in the dbase not be a proper array? What could the problem be? Thanks for any suggestions.
The usual approach to storing an array in this way is to serialize the data before input, and unserialize it upon retrieval.
$array = array('one', 'two', 'three', 'four');
$stringToStore = serialize($array);
Later:
while($row = mysql_fetch_array($res)) {
$array = unserialize($row['list']);
var_dump($array);
}
What you're inserting is not an array, just what PHP has evaluated your array as being in string form. To store an array in MySQL without properly normalizing your data you'll need to serialize it. Basically you'd want to do something like:
$serialized = implode(',', $arrayToStore);
and then store that in MySQL. On its way out then you'll do:
$unserialized = explode(',', $arrayFromMySQL);
I think you can use serialize and also (if you don't use serialize) if your array string is as follows
$str = "one,two,three,four";
then why you are making it an array before inserting it into your database, I think you can insert the string directly and when you need to use your string as an array then you can simply retrieve the string from database and make it an array using explode like
while($row = mysql_fetch_array($res)) {
$array = explode(",", $row['list']); // "one,two,three,four"
echo $array[0]; // one
I have a database table as follows.
<table border='1'><th>Id</th><th>FirstName</th><th>last Name</th><tr><td>1</td><td>Tom</td><td>T</td></tr><tr><td>2</td><td>Jerry</td><td>J</td></tr></table>
I would like to store all values as a multi dimensional array using php(using a while loop to retrieve fields).That is,
I would like the data to be echoed as:
array(array(1,Tom,T),array(2,Jerry,J));
$result = mysql_query("SELECT * FROM tablename;");
while($result_ar = mysql_fetch_array($result)) {
$multid_array[] = $result_ar;
}
after which $multid_array will be an array of arrays.
You can use phps serialize function to convert any variable into a string representation
$string = serialize($dbData);
You can use unserialize() to convert the string back into arrays, objects, etc
$dbData = unserialize($string);
Once you have the data within a string, it's very easy to store in a file, db, etc. A disadvantage is that you won't be able to search your database easily for this data.