PHP array presentation - php

I have an php array with presentation as follow:-
<?php
$ads = array();
$ads [] = array(
'name' => 'Apple',
'duration' => '3',
'price' => "$5"
);
$ads [] = array(
'name' => 'Orange',
'duration' => '2',
'price' => "$10"
);
$ads [] = array(
'name' => 'Banana',
'duration' => '5',
'price' => "$6"
);
and then, I would like to replace the static data with dynamic data from database:-
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
while($record = mysql_fetch_array($result))
{
$fruit_id = $record['fruit_id'];
$fruit_name = $record['fruit_name '];
$fruit_price= $record['fruit_price'];
$fruit_duration= $record_approve['fruit_duration'];
}
Actually, how shall I combine the 2 presentations together? Thanks!

If you want to get a similar structure as the one that you have in the first example, you can modify your second to create a new array and append it to an existing $ads array.
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array(
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']);
}

iteration over result can be modified (provided only the required attributes are fetched in the query)
$fruit = array();
while($record = mysql_fetch_array($result))
{
$fruit[] = $record;
}
may be you could use array_merge
$result = array();
$result = array_merge($ads,$fruit);

So, you want to populate your "ads" array with information from the database? It seems fairly counterintuitive seeing as mysql_fetch_array already returns a perfectly adequate associative array, but here you go:
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[] = array (
'name' => $record['fruit_name'],
'price' => $record['fruit_price'],
'duration' => $record['fruit_duration']
);
}

If
the initial array is not just an example, but default data that you might overwrite with the db data, and
the fruit name is unique (a primary key of sorts)
then you should set the array key of the main array to that of the fruit name, so that if the db has a different value, it will automatically get overwritten but otherwise left alone. Like so:
$ads ['Apple'] = array(
'duration' => '3',
'price' => "$5"
);
$ads ['Orange'] = array(
'duration' => '2',
'price' => "$10"
);
$ads ['Banana'] = array(
'duration' => '5',
'price' => "$6"
);
$sql = "SELECT * from tb_fruit order by fruit_id ASC";
$result = mysql_query($sql_approve, $conn_fruit);
$ads = array();
while($record = mysql_fetch_array($result))
{
$ads[$record['fruit_name']]['price'] = $record['fruit_price'];
$ads[$record['fruit_name']]['duration'] = $record['fruit_duration'];
}
Now, if 'Apple' is in the db, the price and duration get overwritten, but otherwise, it stays where you set it before the query.
You could go a step further and have both the price and duration returned by the query checked for an empty value (Null, "", 0), and only set the value if it is not empty, etc. But that is more a of business logic decision.

Related

How to check if arrays values match while preserving its order in PHP

What I'm trying to do is preserve the order of an array, while determining if each of the numbers match numbers that were pulled from the database. What I have is an array of numbers ($ids), and a non empty array of rows ($rows)
$images = array();
$ids = array(
0 => '41',
1 => '42',
2 => '43',
3 => '44'
);
// database example
$rows = array(
0 => array(
'name' => 'John Doe',
'id' => '42'
),
1 => array(
'name' => 'Jane Doe',
'id' => '43'
),
);
$i = 0;
foreach ($rows as $row) {
// This works, but it doesn't preserve the order of the $ids array
if (in_array($row['id'], $ids[$i])) {
// add $id to a new array
// or use the same $id array
$images[$i]['name'] = $row['name'];
$images[$i]['id'] = $row['id'];
$i++;
}
}
Any help would be appreciated.
Since id is unique in the rows from your database, you can index the $rows array by id to make it easier to look up values there. You can do this with array_column like this:
$rows = array_column($rows, null, 'id');
Or add them to $rows using id as index as you fetch them from the db like this:
while ($row = //whatever query result/prepared statement fetch you're using) {
$rows[$row['id']] = $row;
}
Then, instead of iterating $rows, you can iterate $ids. This will ensure that the resulting $images array will be in the same order as $ids.
foreach ($ids as $id) {
if (isset($rows[$id])) {
$images[] = [
'name' => $rows[$id]['name'],
'id' => $rows[$id]['id']
];
}
}
Another thing that might make this easier (unless you're using the non-matching rows for something else), would be to use the $ids array as a parameter to a WHERE id IN clause in the query that's selecting $rows, so you won't have to do that filtering in PHP. Here's a Q&A that shows how to do that with PDO, for example: PHP - Using PDO with IN clause array.
You could iterate over ids array instead. It will be something like this:
foreach($ids as $id) {
$data = find($id, $rows);
if ($data === null) {
continue;
}
$images[] = [
'name' => $data['name'],
'id' => $data['id']
];
}
function find($id, $rows) {
foreach($rows as $row) {
if($row['id'] == $id) {
return $row;
}
}
return null;
}
Totally agree with #Don't Panic, you should fetch only the data you'll use if possible.

Nested While Loop not working

I am developing a webservice for and android app the webservice is in PHP fetching data from a MySQL database ... The problem that I am having is that some of the projects have multiple details but my code is only fetching one detail for every project. I am getting the data in JSON format.
You can check this Here
Here is my code
function requiredData(){
$db = $this->dbConnection();
//$sql = "SELECT * FROM projects JOIN project_details ON projects.project_id=project_details.project_id";
$sql = "SELECT * FROM projects";
$queryResult = $db->query($sql);
if($queryResult->num_rows > 0){
while($row = $queryResult->fetch_assoc()){
$pid = $row['project_id'];
$detailsql = "SELECT * FROM project_details WHERE project_id=$pid";
$sqlResult = $db->query($detailsql);
if($sqlResult->num_rows > 0){
while ($d = $sqlResult->fetch_assoc()){
$r = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
}
$results[$row['project_name']] = array(
"project_id" => $row["project_id"],
"project_start_date" => $row["project_start_date"],
"project_due_date" => $row["project_due_date"],
"project_currency" => $row["project_currency"],
"project_work_details" => $r
);
}
}
return $results;
}
Thanks in advance for your help
The issue is in the second while loop. You are assigning array to $r, and $r value overwrites every time.
So, I am assigning now array to an other array, So it will become 2 dimensional array, like this;
while ($d = $sqlResult->fetch_assoc()){
$r[] = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
Now you can use $r, it will have multiple details of the project.

PHP function for counting individual rows inside the (MySql) query loop returning null

I would like to include a php function into the query loop which simply outputs all rows from a table.
This function would return another query counting the rows of individual users and would be encoded together with the first query.
The function works, if I echo the userId variable I get it right, but for a reason the count query returns null.
I could use some help, thanks!
<?php
include_once 'includes/db_connect.php';
$query = "SELECT * FROM UPLOADS";
//Creating resonse json array, with another array inside
$jsonResponse = array( "info" =>array() );
if($result = mysqli_query($mysqli, $query)) {
while($row = mysqli_fetch_assoc($result)){
$jsonRow = array(
'user' => $row['USER'],
'userId' => $row['USERID'],
'filename' => $row['FILENAME'],
'description' => $row['DESCRIPTION'],
'location' => $row['LOCATION'],
'address' => $row['ADDRESS'],
'likes' => $row['LIKES'],
'city' => $row['CITY'],
'lat' => $row['LAT'],
'lng' => $row['LNG'],
'countPost' => countUserPosts($row['USERID'])
);
//adding the $jsonRow array to the end of the "users" array as key/value
array_push($jsonResponse["info"], $jsonRow);
}
}
//encoding to json for the app
echo json_encode($jsonResponse);
function countUserPosts($userId){
$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];
return $num;
}
?>
Try to inject the mysqli object inside your function paramater:
function countUserPosts($userId, $mysqli){
// ^ this one so it won't be out of scope.
$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];
return $num;
}

PHP: How to create a jagged array structure to represent grouped records from a database

This seems like a simple challenge, but I'm struggling.
I want to retrieve records using a join query on two database tables and represent them as an array of arrays, whereby each of the elements in the root array is a parent record and each nested element represents a child record.
The SQL query is working fine, and it returns a set of rows in which the channel_key column is a grouping column.
Here's my attempt at populating the array structure from the rows:
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[] = $programme;
if ($key != $row->channel_key) {
$channels[] = array(
'key' => $row->channel_key,
'programme' => $programmes
);
$key = $row->channel_key;
$programmes = array();
}
}
Unfortunately this only populates the root level arrays (the ones that correspond to the parent records).
Any suggestions please?
Thanks,
Tim
You only have one programme in the $programmes array when you assign it to the channel.
An alternative would be to build the channel array with the channel_key.
e.g.
<?php
$channels = array();
foreach($rows as $row) {
// Create the channel node if it doesn't exist
if (!isset($channels[$row->channel_key])) {
$channels[$row->channel_key] = array(
'key' => $row->channel_key,
'programme' => array()
);
}
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
// Add to the existing channel node.
$channels[$row->channel_key]['programme'][] = $programme;
}
Simple solution can be.
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[$row->channel_key][] = $programme;
}

sorting multi dimensional and dynamically created arrays

$feeds = array();
$query = "SELECT * FROM actions WHERE user_id = '$user_id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("feed" => array($info['ID'] => $user_id));
}
$query = "SELECT * FROM follows WHERE user_id = '$id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
$feeds[][$info['date']] = array("follow" => $info['user_id']);
}
I would like to sort that $feeds array in date format (Y-m-d H:i:s) using [$info['date']] key
How can i do that ?
thanks
EDIT:
example of what i want to see as result is
$feeds = array(
0 => array(
'<date>' => array("feed" => array("feed_id" => "user_id"));
),
1 => array(
'<date>' => array("follow" => "user_id" );
),
);
I want to group/sort them in DATE key and do sth depends on if it is FEED or FOLLOW
The best way is to do it in database (faster)!
But if you want do it in PHP, your need uksort (for sorting) + foreach (for grouping) I think

Categories