Adding items to a JSON encoded array - php

I am using this solution found on stackoverflow to encode my MYSQL output to a JSON encoded array.
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
This works great and produces an output of
[{"id":"81","title":"Something Here","start":"2009-10-27 09:00:00"},{"id":"77","title":"Report on water","start":"2009-10-30 09:00:00"}]
Now I need to put a value of say
"colour":"Blue"
within the JSON encoded array.
So i need the ouput to look like
[{"id":"81","title":"Community Awareness","start":"2009-10-27 09:00:00", "colour":"Blue"},{"id":"77","title":"Write a 10,000 Page Report on Emma","start":"2009-10-30 09:00:00", "colour":"Blue"}]
Does anyone have any solutions on how I could achieve this?
Thanks,
Tim Mohr

Before you call json_encode($rows), just edit the value in the $rows array:
$rows[0]['colour'] = 'Blue'; // changes the colour of the first row in the array
edit in fact, if you just want to add a colour to all of the rows, you can do a simple foreach:
foreach ($rows as &$row) {
$row['colour'] = 'Blue';
}

Related

Php append value to an exsisting array

Hi I need to add some value-key pair to an array which is the output of mysql query. Below is the code,
$query = "select TITLE,DESCRIPTION from TABLE where ID='1234'";
$result = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($result);
if($numrows>0)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$myArray[] = $row;
}
}
echo json_encode($myArray);
Giving me the result like
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION."}]
Now I need to to add an another key-value pair to generate the json output like,
[{"TITLE":"Special","DESCRIPTION":"This is DESCRIPTION.","URL":"imgname.jpg"}]
So I added the code
$myArray["URL"]="imgname.jpg";
echo json_encode($myArray);
But giving me the output like,
{"0":{"TITLE":"Chef Special","DESCRIPTION":"Grilled Salmon and crab."},"URL":"imgname.jpg"}
Is there anything wrong with above code.
check your data with
var_dump($myArray);
and you will find, that it is a 2-dimensional array. you'd have to add your data with
$myArray[0]["URL"] = "imgname.jpg";
If you have to add after encoding it, reverse with:
$a = json_decode($myArray,true)
add a new pair of key, value with $a['URL'] = "imgname.jpg" and then encode again.

Imploding to mysqli_fetch_array()

Im new to web development.
I need the array like following
["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
I tried. But I failed.I connected the database. How can I make it?
my array-code
$count=0;
$sql="SELECT name FROM planet";
$sql_run=mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($sql_run))
{
$result[] = "'".implode("\'",$row)."'".",";
echo $result[$count++];
}
By using above code, i couldn't get the result what I expected.
Each fetch returns one planet in associative array. To get array of rows, you have to do:
$list = array();
while($row = mysqli_fetch_assoc($sql_run)) {
array_push($list, $row['name']);
}
var_dump($list);

Merge Mysql Column output as comma seperated in php

I have a simple query with outputs only one column (rows number may change)
SELECT column1 as NUMBER WHERE column1 ...
Output,
NUMBER
1
2
I just want it as an array in PHP with them as comma seperated.
So I did,
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
and its working if I echo it with print_r
However because of some reason I cant get the plain values out of this array.
echo $rows[0] gives me the word 'Array'
echo implode(",", $rows); gives me 1Array',Array1
I tried
echo json_encode($rows[0]);
gives me
["1"]
I simply want 1,2
After a lot of different tries I gave up and added group_concat in the sql query. I just want to know what I did wrong.
Thanks.
try this
SELECT GROUP_CONCAT(`column1` SEPARATOR ',') AS number FROM table where....
mysql_fetch_row i returning a single element array. To have your desired output, only select the 1st element:
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row[0];
foreach($rows as $key => $value){
}
should do the trick, with an echo it will output the results as an associative array
just make a simple amendment to your code:
$rows[] = $row;
into:
$rows[] = $row[0];
and use:
implode(", ", $rows[]);

Best format for JSON encoding?

I'm not familiar with PHP and JSON but need it for my Android project.
I'm confused about which JSON format is the most effective. Most examples I saw use Associative array by using this code:
$result = mysql_query($queryString)
while($row = mysql_fetch_assoc($result)){
$json['contact']['ID'] = $row['ID'];
$json['contact']['Name'] = $row['Name'];
}
Format #1
{"contact":{"ID":"1","Name":"Andy"}}
I like that format but I don't know how to make each key hold more than one value. So when my query returns Andy and Bob, the json will only contains Bob.
Then, I found this PHP code:
while($row = mysql_fetch_row($result)){
$json['contact'][] = $row;
}
echo json_encode($json);
It makes the json looks like this:
Format #2
{"contact":[["1","Andy"],["2","Bob"]]}
But in Android, there is no JSONObject method to getArray(). Even if there is, I want to avoid using numbered array that requires [0] or [1] to be called.
So, which one is better? Or any other alternative?
Thanks
It's not that one method is more "effective" than the other, they serve different purposes. One is an associative object, and the other is a indexed array.
In your case, it looks like you want a list (indexed array) of objects. So what i would recommend doing is:
$result = mysql_query($queryString)
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json['contact'][] = $row;
}
echo json_encode($json);
which would result in the json:
{"contact":[{"ID":"1","Name":"Andy"}, {"ID":"2","Name":"Bob"}]}
Why not use mysql_fetch_array(); ?
{"contacts":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}
An object with key contacts that contain an array of contact objects perhaps?
You can also do it hardcoded (not as nice as mysql_fetch_array() tho.);
$result = array();
$i = 0;
while(...) {
$result[] .= '{"id":"'.$i.'","name":"'.$fetch['name'].'"}';
$i++;
}
echo "[".implode(',', $result)."]";

Variable for each result in WHILE loop SELECT query

I have a question about PHP WHILE loops. I know that you can perform the action mysql_num_rows to get the number of results from a SELECT query.
But say I have 3 results come through the select query and i put them through a while loop, how do I assign a variable to the number each result is in the mysql_num_row.
Such as
1 for result 1
2 for result 2
3 for result 3.
Sorry if this is a bit confusing, but i can't seem to find an easy way to explain it.
Thanks
You do it like this:
$results = array();
While ($row = mysql_fetch_assoc($result))
{
$results[] = $row;
}
$myArray = array();
while($row = mysql_fetch_assoc($result)) {
$myArray[] = $row
}
$res=array();
$i=0;
While(mysql_fetch_array(...)){
$i++;
$res[$i]=value
//do logic
}
There are a few 'new' methods for pulling back data from MySQL now, if you're just starting out this might be the ideal time to have a look at them. This looks like a good place to start: http://www.php.net/manual/en/mysqlinfo.api.choosing.php.

Categories