How to create single JSON for all matching results? - php

I am fetching data from the database, and while I'm fetching, I check for each result if it matches certain criteria, if it does, I want it to add the row with all the details as a new object inside the same JSON, so that I end up with a single JSON that holds all the matching rows
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (matching criteria){
//add row to the JSON
}
}
Right now I can add each row and echo it, but it overwrites the previous row:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (matching criteria){
$firstColumn = $result['firstColumn'];
$secondColumn= $result['secondColumn'];
//more columns if necessary. . .
$myObj->firstColumn = $firstColumn ;
$myObj->secondColumn= $secondColumn;
$myJSON = json_encode($myObj);
echo $myJSON;
}
}

you can use PDO::fetch_object for ever row and add them to assoc array/another object and then use the json_encode on it.
something like (pseudocode not tested) it will create json array with object for every row:
$out = [];
while($result = $stmt->fetch(PDO::FETCH_OBJ)
{
if(matching){
$out[] = $result;
}
}
echo json_encode($out);

Try this way create a array assign value to that array with myObj Data and after get collection of array convert into Json object
$data = array(array());
$i = 0;
$j = 0;
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if (matching criteria){
$firstColumn = $result['firstColumn'];
$secondColumn= $result['secondColumn'];
//more columns if necessary. . .
$myObj->firstColumn = $firstColumn ;
$myObj->secondColumn= $secondColumn;
$data[i][j]=$firstColumn;
$j++;
$data[i][j]=$secondCoulmn;
$i++;
$j--;
}
}
$myJSON = json_encode($data);
echo $myJSON;

Related

Expand (json) object in php

I want this sql-query result (from a log file, i hope it's accurate)
[
{"id":"1","text":"123"}
,{"id":"2","text":"456"}
] []
to become this
{
1: {"id":"1","text":"123"}
,2: {"id":"2","text":"456"}
}
I tried array_push and array_combine but am new to PHP and was unsuccessful so far.
Short: I want to add keys (starting with 1) to an array of objects.
One attempt
$i = 1;
while ($row = fetchRow($result)) {
array_push($arr_result, $row);
array_push($i, $arr_result);
$i++;
}
But $arr_result looks like the first code sample.
You dont need $i using $arr_result[] will create a new occurance in your array.
while ($row = fetchRow($result)) {
// this forces the array to start at 1 instead of 0 if thats what you really want
if (count($arr_result) == 0){
$arr_result[1] = $row;
} else {
$arr_result[] = $row;
}
}
Or if the key is supposed to be the id from the row
while ($row = fetchRow($result)) {
$arr_result[$row['id']] = $row;
}

I want to match my array value to a column value from a table in php

date_default_timezone_set('Asia/Kolkata');
header('Access-Control-Allow-Origin: *');
include_once('conn.php');
$data2 = array();
$content = trim(file_get_contents("php://input"));
$data = json_decode($content);
$couplenumber = $data->contact_number;
$sql = "SELECT * from `users_table` where `phone` IN '$couplenumber'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($data2, $row);
}
echo json_encode($data2);
} else {
echo 0;
}
$conn->close();
$couplenumber is an array it has multiple contact numbers. I want to match my array value to the table column named the phone. The phone has a string value that means a single contact. How I can get data after match phone value to multiple contacts of $couplenumber value?
It will be better, if you show us your arrays content. But, if you have some things like one objects array and one array with ids only, let's try it:
//Arrays are like :
$tab1 = [3,4];
//Considering Object is a class which receive id in constrictor and has et getId method.
$obj1 = new Object(1);
$obj2 = new Object(2);
$items = [$obj1, $obj2];
$tab2 = [];
foreach ($items as $item) {
$tab2[] = $item->getId();
}
$diff = array_merge(array_diff($tab1, $tab2), array_diff($tab2, $tab1));
// True there are same, false there differents.
var_dump( empty($diff) && (count($tab1) === count($tab2)) );

PHP: show only last data from same data on loop

i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}

how to add extra element to array with array_push in PHP?

I am developing in PHP/MS SQL for getting JSON Response.
Code which I wrote is:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$array_res[] = $result; // add result to array
array_push($array_res, array('unidad' => $uni)); // add extra element
$jsonObj = json_encode($array_res); // encode JSON
}
echo $jsonObj;
exit();
This is what I want in result:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null,"unidad":1}]
but the result shows me this:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null},{"unidad":1}]
You're fetching an object. Add $uni to $result first and then add to $array_res:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$result->unidad = $uni;
$array_res[] = $result;
}
Also, you probably want the json_encode() after the loop not in the loop:
echo json_encode($array_res);

add array element to row returned from sql query

I want to add an additional value into an array before passing it to json_encode function,
but I can't get the syntax right.
$result = db_query($query);
// $row is a database query result resource
while ($row = db_fetch_object($result)) {
$stack[] = $row;
// I am trying to 'inject' array element here
$stack[]['x'] = "test";
}
echo json_encode($stack);
If it's an array you can directly add a value:
$row['x'] = 'test';
$stack[] = $row;
if it's an object you can add another property:
$row->x = 'test';
$stack[] = $row;
if you want to keep the object and the extra value separated:
$data = array($row, 'x' => 'test');
$stack[] = $data;
but this does work.
$stack[] = $row;
$row->x = 'test';
How about something like:
$row['x'] = 'test';
$stack = $row;

Categories