Make a multidimensional array through loop! - php

How can i make an array like below through a loop? The text will generated from database!
$listofimages = array(
array( 'titre' => 'PHP',
'texte' => 'PHP (sigle de PHP: Hypertext Preprocessor), est un langage de scripts (...)',
'image' => './images/php.gif'
),
array( 'titre' => 'MySQL',
'texte' => 'MySQL est un système de gestion de base de données (SGDB). Selon le (...)',
'image' => './images/mysql.gif'
),
array( 'titre' => 'Apache',
'texte' => 'Apache HTTP Server, souvent appelé Apache, est un logiciel de serveur (...)',
'image' => './images/apache.gif'
)
);

do something like this,
$result = mysql_query("SELECT * FROM table;");
while($row = mysql_fetch_assoc($result) {
//$row will hold all the fields's value in an array
$mymainarray[] = $row; //hold your array into another array
}
//To display
echo "<pre>";
print_r($mymainarray);
echo "</pre>";

Something like :
$listofimages = array();
foreach ( $rowset as $row ) {
$listofimages[] = array(
'titre' => $row['titre'],
'texte' => $row['texte'],
'image' => $row['image']
);
}
?

If you only select the fields titre, texte and image in your query, then it is just (assuming MySQL):
$listofimages = array();
$result = mysql_query("SELECT titre, texte, image FROM table");
while((row = mysql_fetch_assoc($result))) {
$listofimages[] = $row;
}
mysql_fetch_assoc() will fetch the results in an associative array.

Let's say you have done a query and get a result identifier:
$result = mysql_query("SELECT * FROM table;");
Now you can get every row as an array by using mysql_fetch_assoc($result). Now just make a final array and add all these arrays to it:
$final_array = array();
while($row = mysql_fetch_assoc($result) !== false) {
$final_array[] = $row;
}
print_r($final_array);

$mult_array = array();
$result = mysql_query("SELECT col1,col2,... FROM table");
if(mysql_num_rows($result)>0){
while((row = mysql_fetch_assoc($result)) {
$mult_array[] = $row;
}
}
// if u want to pick some specific cols from data selected from database then-
if(mysql_num_rows($result)>0){
$temp_arr = array();
while((row = mysql_fetch_assoc($result)) {
$temp_arr['col1'] = $row['col1'];
$temp_arr['col2'] = $row['col2'];
//... so on
$mult_array[] = $temp_arr;
}
}

foreach ($listofimages as $image) {
echo '<img src="'.$image['image'].'" />';
}

Related

I have a question about JSON PHP Multi Values

I want to select the database more values (I already did) and be converted to JSON
I tried all
php
$a = $_GET['name'];
header('Content-Type: application/json');
echo '{"results":[';
$selectSearch = "SELECT * from `users` WHERE `name` LIKE '".$a["term"]."%'";
$rezultatul = $db->query($selectSearch);
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
echo json_encode($arr);
}
}
echo ']}';
And he looks like this:
{"results":[{"id":"1","text":"Pompiliu","level":"7"}
{"id":"11","text":"Pompiliu1","level":"100"}]}
But between the two must be like that
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"}
And when there will be 3 results
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"},
{"id":"12","text":"Pompiliu2","level":"100"}
Add to the array with [] and then json_encode.
Don't try and build json strings on your own.
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr[] = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
}
}
echo json_encode(["results" => $arr]);

How can I encode a json of a multiline result?

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);
}

How to json encode a single object as a json objects array using PHP

For two objects:
{"publications":[{"nom":"toto","id":"2029","userid":"22","publication":"bla bla bla","time":"2017-02-20 00:00:00","avatar":{}},{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}]}
For One object:
{"publications":{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}}
i want to have always a json array as a return no matter how the number of objects.
PHP Code:
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$mydata = $json->addChild('publications');
$mydata->addChild('nom',$row['nom']);
$mydata->addChild('id',$row['id']);
$mydata->addChild('userid',$row['userid']);
/*echo(utf8_encode($row['publication']));*/
$mydata->addChild('publication',utf8_encode($row['publication']));
$mydata->addChild('time',$row['time']);
$mydata->addChild('avatar',$row['avatar']);
}
echo( json_encode ($json));
} else {
echo "0";
}
Well you are not using XML for anything else but convert it to JSON, so there is no need for XML. Use array
$result = $conn->query($sql);
$json = ['publications' => []];
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$json['publications'][] = [
'nom' => $row['nom'],
'id' => $row['id'],
'userid' => $row['userid'],
'publication' => $row['publication'],
'time' => $row['time'],
'avatar' => $row['avatar']
];
}
echo json_encode($json);
}
else
{
echo "0";
}
It's a particluar behaviour of SimpleXML.
If you have one child in xml - you will have an object in json, if you have more than one child - you will get array of objects. So, I advise you to rewrite your code using simple arrays instead of xml-approach:
$result = $conn->query($sql);
$json = []; // just array
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// add new item
$json[] = $row;
// or more specifically
$json[] = [
'nom' => $row['nom'],
'id' => $row['id'],
// more fields that you need
];
}
}
echo json_encode(['publications' => $json]);

Display multiple data row and display json data

I need to display multiple data row and display json data. Here is my code:
<?php
$dinner_food_category=$_GET['DinnerFoodCategory'];
$conn = mysqli_connect("localhost","taig9_gen_user","GenAdmin1/Pass");
if($conn) {
$select_database = mysqli_select_db($conn,"taig9_genumy");
$select_query = "SELECT food_id,food_name,serving_type,serving_type_amount,singal_unit_weight FROM food_details WHERE category_id IN ('VEG00','VGB00','SUP00','CAK00')";
$result = mysqli_query($conn, $select_query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$foods_id=$row['food_id'];
$foods_name=$row['food_name'];
$foods_type=$row['serving_type'];
$foods_type_amount=$row['serving_type_amount'];
$singal_unit_weights=$row['singal_unit_weight'];
}
$data = array("FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights);
}
echo stripslashes(json_encode($data));
}
?>
On each iteration of while you food_ variables are overwritten, and after while loop is over - you have value for the last row only. To avoid this you should add variables to $data inside a while loop with [] notation:
while ($row = mysqli_fetch_assoc($result)) {
$data[] = array(
"FoodId" => $row['food_id'];
"FoodNames" => $row['food_name'];
"FoodType" => $row['serving_type'];
"FoodAmount" => $row['serving_type_amount'];
"SingalUnitWeight" => $row['singal_unit_weight'];
);
}
// using `stripslashes` is useless
echo json_encode($data);
if (mysqli_num_rows($result) > 0) {
$data = [];
foreach ($result as $row) {
$foods_id=$row['food_id'];
$foods_name=$row['food_name'];
$foods_type=$row['serving_type'];
$foods_type_amount=$row['serving_type_amount'];
$singal_unit_weights=$row['singal_unit_weight'];
$data[] = ["FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights];
}
echo stripslashes(json_encode($data));
}

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"]]}

Categories