i have this code and i want to return an array of object and inside that object an associative array.
something like this
[
{"ids":["id1",'id2','id3'],
"item":["name","name2","name3"]},
{"ids":["id4",'id5','id6'],
"item":["name4","name5","name6"]},
{"ids":["id1114",'id1115','id1116'],
"item":["name11114","name11115","name1116"]},
]
it sends the objects with the array but it only has the last element in the array
//get customers of single item
if($this->connect()->connect_error){
echo die("Connection failed: " . $this->connect()->connect_error);
}else{
for($i=0; $i<count($final_array['item']); $i++){
$single = $final_array['item'][$i];
$sql = "SELECT ACCT_ID, PARTS_EXPIRY, dcii_item, dcii_desc, dcii_acct_id, dcii_qty AS QTY
FROM dos_account AS DOS
JOIN dos_client_invoice_items as DOS2
ON DOS.ACCT_ID = DOS2.dcii_acct_id
WHERE dcii_item = '$single'
AND DOS.PARTS_EXPIRY BETWEEN '$start' AND '$end'
ORDER BY DOS.PARTS_EXPIRY";
$result = $this->connect()->query($sql);
$numRows = $result->num_rows;
if($numRows > 0){
// $array_container = [];
while($row = $result->fetch_assoc()){
$item[] = $row['dcii_item'];
$acctID[] = $row['ACCT_ID'];
$array_container5 = array();
$array_container5[] = $row['dcii_item'];
$array_container = array();
$array_container[] = $row['ACCT_ID'];
//array_push($array_container, $row['dcii_item']);
}
$array_container2['item'] = $array_container5;
$array_container2['ids'] = $array_container;
$final_array['objectContainer'][] = $array_container2;
}
}
$jsonData = json_encode($final_array);
echo $jsonData;
}
Related
Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?
<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
$masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
$r['masp'] =$data['masp'];
$r['loai'] =$data['loai'];
$r['hangsx']=$data['hangsx'];
$r['tensp']=$data['tensp'];
$r['img']=$data['img'];
$r['gia']=$data['gia'];
$r['nx']=$data['nx'];
}
}
}
print json_encode($data);
?>
You are setting your variables wrong.
In every while cycle you get a new $r variable that you want to add to your $data variable.
$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
$masp = $_GET['masp'];
$sql = "SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn, $sql);
$i = 0;
if ($result) {
while ($r = mysqli_fetch_assoc($result)) {
$data[$i]['masp'] = $r['masp'];
$data[$i]['loai'] = $r['loai'];
$data[$i]['hangsx'] = $r['hangsx']];
$data[$i]['tensp'] = $r['tensp'];
$data[$i]['img'] = $r['img'];
$data[$i]['gia'] = $r['gia'];
$data[$i]['nx'] = $r['nx'];
$i += 1;
}
}
}
print json_encode($data);
You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r;
i had this php code :
<?php
include "../mainmenu/koneksi.php";
// Start with the list of animals
$sql = "SELECT * FROM data_binatang";
$rows = array();
$res = mysql_query($sql);
for($i=0; $i<mysql_num_rows($res); ++$i){
$row1 = mysql_fetch_assoc($res);
$id_binatang = $row1['id_binatang'];
$sql = "SELECT * FROM data_waktu_vaksinasi WHERE id_binatang = $id_binatang AND (status_vaksin = 'belum' OR status_vaksin IS NULL) ORDER BY tanggal_vaksin ASC LIMIT 1";
$res2 = mysql_query($sql);
$row2 = mysql_fetch_assoc($res2);
$arr[$id_binatang] = array();
array_push($arr[$id_binatang], $row1['nama_binatang'], $row1['id_user'], $row1['jenis_binatang'], $row1['ras_binatang'], $row1['foto_binatang'], $row2['nama_vaksin'], $row2['id_data_waktu_vaksinasi'], $row2['status_vaksin'], $row2['tanggal_vaksin'], $row2['tanggal_datang']);
}
echo "RESULT:";
echo "<table border=1><tr><th>id binatang</th><th>nama binatang</th><th>id user</th><th>jenis binatang</th><th>ras binatang</th><th>foto binatang</th><th>nama vaksin</th><th>id data waktu vaksin</th><th>status vaksin</th><th>tanggal vaksin</th><th>tanggal datang</th></tr>";
foreach($arr as $key => $val){
echo "<tr><td>$key</td><td>".implode("</td><td>", $val)."</td></tr><br>";
}
?>
and here's the result
now i want to generate the table into json, but i don't know what to put inside the json encode, i tried:
echo '{"data_vaksinasi_menu":'.json_encode($arr[$id_binatang]).'}';
but instead it gave me null
Try this:
echo json_encode(array('data_vaksinasi_menu' => $arr));
Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.
MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}
i would like to store data from a form into 2D array
but it seems to have problem inserting data into the array.
if i were to echo $orderArray[0][$count2] it seems to work
but if i were to echo $orderArray[1][$count2] there will be error
$dateArray = array();
$orderArray = array(array());
$amountArray = array(array());
$count = 0;
$count2 = 0;
foreach ($_POST['export'] as $date){
$dateArray[$count] = $date;
include "/storescript/connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM ordera WHERE orderDate = '$date' ORDER BY orderid ASC");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$orderArray[$count][$count2] = $row["orderAmount"];
$amountArray[$count][$count2] = $row["itemAmount"];
$count2++;
}
}
$count++;
}
I would reduce the code to this:
// connect here
include "/storescript/connect_to_mysql.php";
// make date list safe for querying
$dates = join(',', array_map(function($date) {
return sprintf("'%s'", mysql_real_escape_string($date));
}, $_POST['export']);
// run query
$sql = "SELECT * FROM ordera WHERE orderDate IN ($dates) ORDER BY orderid";
$res = mysql_query($sql) or die("Error in query");
// collect results
while ($row = mysql_fetch_array($res)) {
$orders[$date][] = $row['orderAmount'];
$amounts[$date][] = $row['itemAmount'];
}
// do stuff with results
foreach ($orders as $date => $orderAmounts) {
print_r($orderAmounts);
print_r($amounts[$date]);
}
Also, please learn about PDO or mysqli; the old mysql_ functions are deprecated.