How can I encode a json of a multiline result? - php

I try to encode my result in a json but it doesn't really work. When the query has more than one result than it doesn't work. When the result has only one line, than everything works fine.
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
$array = array();
while ($row = mysqli_fetch_assoc($sql)) {
$array[] = array (
'label' => $row['a'].', '.$row['b'],
'value' => $row['a'],
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
}

Try this code
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
$array = array();
$i = 0;
while ($row = mysqli_fetch_assoc($sql)) {
$array[$i] = array (
'label' => $row['a'].', '.$row['b'],
'value' => $row['a'],
);
$i++;
}
//RETURN JSON ARRAY
echo json_encode ($array);
}

Related

How to convert JSON string to arrays

With php, I need to convert json arrays into arrays, what should I do, json_encode didn't work for me, thanks in advance for help.
//json sequence
[
{
"name":"Menu",
"sub":
[
{
"name":"Menu 2",
"url":"menu-2.php"
}
]
}
]
this way i should do
array(
'name' => 'Menu',
'sub' => array(
array(
'name' => 'Menu 2',
'url' => 'menu-2.php'
)
)
)
i am creating json array with this function
Do I have to make a change here? I'm not really good in arrays.
<?php
$connect = new PDO("mysql:host=localhost; dbname=propanel_001", "root", "");
$parent_category_id = "";
$query = "SELECT * FROM tb_sayfalar";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$data = get_node_data($parent_category_id, $connect);
}
echo json_encode(array_values($data));
function get_node_data($parent_category_id, $connect)
{
$query = "SELECT * FROM tb_sayfalar WHERE parent_id = '".$parent_category_id."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$sub_array = array();
if (array_values(get_node_data($row['id'], $connect))) {
$sub_array['name'] = $row['page_name'];
$sub_array['sub'] = array_values(get_node_data($row['id'], $connect));
}else{
$sub_array['name'] = $row['page_name'];
$sub_array['url'] = $row['page_url'].".php";
}
$output[] = $sub_array;
}
return $output;
}
?>
This is what you need, json_decode($json,true);
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = json_decode($json,1);
print_r($array[0]);
?>
DEMO: https://3v4l.org/JZQCn
OR use it as a parsable string representation of a variable with var_export()
<?php
$json = '[{"name":"Menu","sub":[{"name":"Menu 2","url":"menu-2.php"}]}]';
$array = var_export(json_decode($json,1)[0]);
print($array);
?>
DEMO: https://3v4l.org/rLA9R
You must use json_decode to convert JSON representing Object to Associative array.
Example Code
$resArr = json_decode($response, true);
For more information look at PHP JSON_DECODE

how can i use values in array ? (php)

I wanna use values in array of array like:
$result = $conn->query("SELECT performer,file_id,title,duration FROM
databasebot WHERE performer = '$message' or title = '$message'");
$poets = array(
"keyboard" => array()
);
while ($row = mysqli_fetch_row($result)) {
$poets['keyboard'][] = array($row[2],$row[1]);
}
I wanna echo $poets values of $row[1]. How can I do that?
Loop through the array in $poets['keyboard']. In each element, $poets[1] will be in the [1] sub-element.
foreach ($poets['keyboard'] as $kb) {
echo $kb[1];
}

Change JSON format php

I have this php code that i need to change the JSON format i get the data from a mysql db:
// Retrieve data from database
$sql="SELECT nombre FROM deudores ORDER BY fecha ASC LIMIT 10";
$result=mysqli_query($con, $sql);
$emparray = array();
// Start looping rows in mysql database.
while($rows=mysqli_fetch_assoc($result)){
$emparray[] = $rows;
// close while loop
}
//print_r($emparray);
//echo json_encode($emparray);
$output = array(
'c2array' => true,
'size' => array(
0 => count($emparray),
1 => 1,
2 => 1
),
'data' => array()
);
$x = 0;
foreach ($emparray as $value) {
$output['data'][$x] = array();
$output['data'][$x][0] = array();
$output['data'][$x][0][0] = $value;
$x++;
}
echo json_encode($output);
That code print this JSON:
{"c2array":true,"size":[7,1,1],"data":[[[{"nombre":"test"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"test"}]],[[{"nombre":"test"}]],[[{"nombre":"oscar"}]],[[{"nombre":"Oscar"}]]]}
but i need the JSON to look like this:
{"c2array":true,"size":[7,1,1],"data":[[[test]],[[Oscar]],[[Oscar]],[[test]],[[test]],[[oscar]],[[Oscar]]]}
How can i achive this?
Thanks in advance!
Use mysql_fetch_row() instead of mysql_fetch_assoc.
while($rows=mysqli_fetch_row($result)){
$emparray[] = $rows;
// close while loop
}
And just set $emparray as value for $output['data']. No need extra work!
$output['data'] = $emparray;
This should make the output like this :
{"c2array":true,"size":[7,1,1],"data":[["test"],["Oscar"],["Oscar"],["test"],["test"],["oscar"],["Oscar"]]}

MySQLi - search through an array

I have the following code:
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();
Brings back the following (only an excerpt):
Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.
What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:
WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number
How do I search through the array, normally, I'd use something like:
if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}
But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.
You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE.
To do this rewrite your query like this.
$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';
echo $row[0]['qcount']; //return 118
if you still want to it with PHP after getting the result from the database, it's how it done:
function get_q17_count($rows, $q17){
foreach ($rows as $onerow) {
if($onerow['q17'] == $q17){
return $onerow['COUNT(q17)'];
}
}
}
function resultToArray($results) {
$rows = array();
while($row = $results->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['q17'] === $id) {
return $val['COUNT(q17)'];
}
}
return null;
}
Called the function using:
$id = searchForId($q[$i], $rows);echo " (".$id.")";

How can i put my database result in 3 dimensional array?

This is my code
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
is there any way to extract title,text,date from $result and put them into 3 dimensional array?
What about
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$array = array();
$i = 0;
while( $row = mysql_fetch_assoc( $result ) {
$array[$i] = array();
// i'm just guessing at what sort of array you want
$array[$i][$row['title'] = array( 'text' => $row['text'], 'date' => $row['date'] );
$i++;
}
I'd be interested to know what the ... you need a three-dimensional array for but ok:
$dim = array();
$result = mysql_query(...);
while ( $row = mysql_fetch_assoc($result) )
// Whatever you want to save in that particular bucket,
// I'll be using the result set
$dim[$row['title']][$row['text']][$row['date']] = $row;
Strange, ...
If we are already guessing, here is mine:
$results = array();
while(($row = mysql_fetch_assoc($result))) {
$results[] = $row;
}
which will create an array like this:
array(array('title' => 'foo',
'text' => 'bar',
'date' => 'baz'),
//...
)
I think what you're after is actually a two-dimensional array (in which the second dimension has three elements). (Correct me if I'm wrong.)
One of the comments under the documentation of mysql_fetch_array has an answer to this:
(Disclamer: This code is unnecessarily verbose. I prefer not changing it though as I have copied it from the above web-page. For improvements, I refer to the comments.)
<?php
function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
$i=0;
$keys=array_keys(mysql_fetch_array($result, $numass));
mysql_data_seek($result, 0);
while ($row = mysql_fetch_array($result, $numass)) {
foreach ($keys as $speckey) {
$got[$i][$speckey]=$row[$speckey];
}
$i++;
}
return $got;
}
?>
You should then be able to use this function as
<?
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT title,text,date FROM news limit 5");
$arr = mysql_fetch_rowsarr($result);
$row_2_title = $arr[2]['title'];
?>

Categories