foreach -> array -> json - Group them together - php

I'm trying to get an output in json, but currently I have a to either group them together, or remove the key in the json output.
$output = array();
foreach ($data->results() as $data) {
$output[]['id'] = $data->id;
$output[]['userid'] = $data->userid;
$output[]['title'] = $data->title;
}
echo json_encode($output);
This current code will out following, but they don't group in id, userid and title as I would like it to do.
[{"id":"31"},{"userid":"1"},{"title":"Test 1"},{"id":"52"},{"userid":"1"},{"title":"Test 2"},{"id":"53"},{"userid":"1"},{"title":"Test 3"},{"id":"58"},{"userid":"1"},{"title":"Test 4"}]
I then tried to do it in another way, by giving the array a key to group them, but my problem is that the system dont regonize the code then, if they have the ID as key.
$output = array();
foreach ($data->results() as $data) {
$id = $data->id;
$output[$id]['id'] = $data->id;
$output[$id]['userid'] = $data->userid;
$output[$id]['title'] = $data->title;
}
{"31":{"id":"31","userid":"1","title":"Test 1"},"52":{"id":"52","userid":"1","title":"Test 2"},"53":{"id":"53","userid":"1","title":"Test 3"},"58":{"id":"58","userid":"1","title":"Test 4"}}
I would like it to remove the key which I have input. Currently I can't really think of a way to do it.
As Anant requested:
The output for $data->results() is all the informations from my database in a table. The problem is that I would like to change either the array $data->results(), but could not find a method for that, so choose to play around with this method instead shown above.
[{"id":"31","userid":"1","title":"Test 1"},{"id":"52","userid":"1","title":"Test 2"},{"id":"53","userid":"1","title":"Test 3"},{"id":"58","userid":"1","title":"Test 4"}]

Just create the new array in one step
$output = array();
foreach ($data->results() as $data) {
$output[] = array(
'id' => $data->id,
'userid' => $data->userid,
'title' => $data->title);
}
echo json_encode($output);

Related

json_encode array of data from DB

I am not sure how to write the following code.
$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
$jsonArray = array(
'listing_number' => $listing['listing_number'],
);
exit(json_encode($jsonArray));
}
When I do it like that, the response is Undefined Index: listing_number.
However, If I write it like this,
$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
$jsonArray = array(
'listing_number' => $listing[0],
);
exit(json_encode($jsonArray));
}
The response is
{"listing_number":{"id":"24","client_id":"1","address":"","address_2":"","city":"","state":"","zip":"","price":"","listing_number":"asdasdasdasd","remarks":"","link":"","status":"","bd":"","ba":"","lot_sz":"","sq_ft":"","yr":"","type":"","thumb":""}}
Which lets me know my SQL is and PHP is correct, I just don't know how to access $listing['listing_number] correctly.
Any help would be appreciated.
as GrumpCrouton said in the comment, your query is returning an array of results. So if you want to access a value in the first result, you first need to access this result using it's index : $listing[0]->listing_number.
$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
$jsonArray = array(
'listing_number' => $listing[0]->listing_number,
);
exit(json_encode($jsonArray));
}
P.S. You can convert object to array using a simple cast ( $result = (array) $result ), but it is not a must in your case. Casting your object to array will allow you to acces it's data using result['key'] rather than result->key.

When I try to access to array items I only get the 1. one

Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.

SQL - Separate results by associated vale?

Before anything, I'll show you my table:
(In the context of PHP)
I'd like to create a multidimensional array via a query - So that a group of tags with the same id will end up in the same place:
<?php
// Given the above example table, it would essentially produce this:
$my_1 = array
( array('ect'),
array('123', 'tag'),
array('lolly', 'hat')
);
Is that a possibility? I've achieved the same result by looping through queries, but it's terribly inefficient.
<?php
$array = array();
foreach($tags as $tag)
{
if(array_key_exist($tag->id,$array)){
//if key is assigned in array, we can push value to key
$array[$tag->id] = array_push($tag->value,$array[$tag->id]);
}else{
//if key is not assigned we will create key and push value
$array[$tag->id] = $tag->value;
}
}
//usage
print_r($array[7]); // list tags with id 7
?>
Use a 2-dimensional array:
$array = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$tag = $row['tag'];
if (isset($array[$id])) {
$array[$id][] = $tag;
} else {
$array[$id] = array($tag);
}
}
The resulting $array will be
array(1 => array('ect'),
7 => array('123', 'tag'),
9 => array('lolly', 'hat'))

How do you append to a PDO resultset array or Json_encoded string?

I want to add a bit more information to a json object before sending it back to my app.
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
echo '{"items":'. json_encode($res) .'}';
The PDO query returns a result set like this when I echo($res)
Array{"items":[{"uid":"10","repo":"bnef"}]}
then it gets encoded back to jquery- echo '{"items":'. json_encode($res) .'}';
giving me
{"items":[{"uid":"10","repo":"bnef}]}
I'd like to add "isnew":"1" to that but when I try
$res['isnew']="1"; or array_merge I end up with
{"items":{"0":{"uid":"10","repo":"bnef"},"isnew":"1"}}
which doesn't work. I need
{"items":[{"uid":"10","repo":"bnef, "isnew":"1"}]}
Am I misguide in try to do this?
I misread your question and got confused on the code... you shoudl incat be dealign with an array initially try the following:
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$items = $q->fetchAll(PDO::FETCH_OBJ);
// you actually wnt isnew as a property of each row
// so you need to loop over the results
foreach($items as $key => $item){
$item->isnew = 1;
}
echo json_encode(array(
'items' => $items
));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
Its not working because you used FETCH_OBJ instead of FETCH_ASSOC so youre wokring with an StdObject instance not an array. In that case you need to use -> to assign:
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res->isnew = "1";
Alternatively you could fetch as an associative array:
$res = $q->fetchAll(PDO::FETCH_ASSOC);
$res['isnew']="1"; //this will work now
Additionalyl i wouldnt try to manipulate the JSON serialized string. I would doo all modifications natively:
$items = array(
'items' => $res
);
echo json_encode($items);

Adding items to a multi-dimensional array during query while loop

I have a query returning data that looks like this:
Status Total
Success 234
Failed 20
Missing 12
I want to add this to an array which can then be used to populate a google pie chart.
the array would look like this:
array backup = array("Success" => 234),
("Failed" => 20),
("Missing" => 12);
How would I add these item dynamically at each row in a query?
$result = mysql_query(...);
$backup = array();
while ($r = mysql_fetch_assoc($result)) {
$backup[$r['Status']] = $r['Total'];
}
Here's how you can make the Google Charts API call:
$values = implode(',', array_values($backup));
$labels = implode('|', array_keys($backup));
$img = "http://chart.apis.google.com/chart?cht=p3&chd=t:{$values}&chl={$labels}&chs=250x100";
echo "<img src='{$img}' alt='Chart'>";
Assuming this is your query:
SELECT status, total FROM table
Then you can do:
$data = array();
while(($row = mysql_fetch_assoc($result))) {
$data[$row['status']] = $row['total'];
}
If this is not what you mean, please clarify your question and/or provide the code you already have.
I think we need a bunch more information, but in the mean time look at array_merge()
http://www.php.net/manual/en/function.array-merge.php

Categories