I am making an image website and I need help with timestamp sorting. I have about 5 different SQL queries to get information from the database. Each one of these queries get the timestamp.
What I want to do is get it from the database, and sort the images from all of the queries with a foreach loop. This may sound confusing, just comment if you don't understand.
$images = array();
$stmt = $conn->prepare("SELECT images.*, group_images.* ORDER BY `timestamp` DESC");
$stmt->execute();
while ($images_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$images[] = array(
'image_id' => $images_row['image_id']);
}
return $images;
foreach($images as $image) {
echo $image['image_id'];
echo '<br/>';
}
That is a query I attempted to try which turned out not to work.
Error:
$images = valley_images();
$sorted_data = array();
foreach($images as $key => $value) {
if ($key == 'timestamp') {
$sorted_data[$value][] = $images;
}
}
ksort($sorted_data);
If I understand you correctly, this might help:
$data; //data from database, assuming it has a "timestamp"-key
$sorted_data = array();
foreach ($data as $key => $value) {
if ($key == 'timestamp') {
$sorted_data[$value][] = $data;
}
}
ksort($sorted_data);
With that you get an array that is ordered by the timestamps of your values from the database. If there is only one entry to each timestamp you can spare the [].
Related
I have an array data where I am storing the result of an SQL query as below :
$stmt = sqlsrv_query($db,$sql);
$data = [];
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
if(!empty($row)) { $data[] = $row; } }
then I want to create a group key which is the concatenation of specific keys of my array data as below :
foreach ($data as $d) {
$group_key = $d['id'].'_'.$d['Country'].'_'.$d['Order Numer'];
//rest of my code
}
it works fine but I want to choose the keys dynamically instead of setting up manually id, Country and Order Number...
let's say I have an array $PostKeys = ["id","Country","Order Number"]; this array will vary depending on the values selected by user...
What I did is :
$PostKeys = ["id","Country","Order Number"];
foreach ($data as $d) {
foreach($PostKeys as $value)
{ $array_group_key[] = $d[$value] ; }
$group_key = implode("_",$array_group_key);
// rest of my code
}
I am supposed to get the same result but there is always mismatch. I didn't figure out where is the issue exactly. Any suggestions please ? Thank you very much.
You need to empty $array_group_key each time through the loop. Otherwise, you're appending to the results from all the previous rows.
foreach ($data as $d) {
$array_group_key = [];
foreach($PostKeys as $value)
{
$array_group_key[] = $d[$value] ;
}
}
I have an array of data that is being created from a MySQL query which I am then using to create more data which I then need back in the array (or a new one) but I haven't been able to get this working at all.
Here is the code I have been trying to use:
$vars['items'] = $this->_query('SELECT customers.*, sites.site_name as `default_location`
FROM `customers`
JOIN `sites` ON customers.site_id=sites.id');
$a=array();
foreach($vars['items'] as $customer)
{
if($customer['record_to_use'] == '2')
{
$results = dns_get_record($customer['cust_mx'], DNS_MX);
$mx = min(array_column($results, "pri"));
$highest = array_filter(
$results,
function($item) use($mx) {return $item["pri"] === $mx;}
);
foreach ($highest as $mx)
{
$results = dns_get_record($mx["target"], DNS_A);
foreach ($results as $a)
{
$vars['items']['ip'] .= $a['ip'];
}
}
}
}
So I need the IP that gets created from each item in the array to get added into that array as $vars['items']['ip']
Thanks in advance!
foreach ($results as $a => $value)
{
$vars['items'][$a]['ip'] = $value['ip'];
}
That's what I needed :)
$vars['items']['ip'] .= $a['ip'];
.= is concatenation if that was a typo in your code.
Try $vars['items']['ip'] = $a['ip'];
I have 3 tables, the first one is table name Post, the second is comment, and third is defineComment. I want to show all 3 tables, but my code is too long. Could you please advice me?
$r = $this->w->listwall();
if($r)
{
foreach($r as $key)
{
// load comment to view data
$pc['pc_comment'] = $this->w->get_comments($key['p_id']);
$data['wall'][] = [
'u_id'=>$key['u_id'],
'p_id'=>$key['p_id'],
'u_fname'=>$key['u_fname'],
'u_lname'=>$key['u_lname'],
'p_text'=>$key['p_text'],
'p_date'=>$key['p_date'],
'u_pf' =>$this->pf->getprofile($key['u_id']),
'p_img'=>$this->w->getimg($key['p_id']),
'cover'=>$this->w->getcoverimg($key['p_id']),
'bgpf' =>$this->w->getbgimg($key['p_id']),
'p_link'=>$key['p_link'],
'pc_comment'=>$this->w->get_comments($key['p_id']),
'pc_count'=>$this->w->get_count_comment($key['p_id']),
'pc'=>$this->load->view('wall/v_comment_wall', $pc, TRUE),
'p_like'=>$this->w->get_list_like($key['p_id']),
'count_like'=>$this->w->count_like_post($key['p_id'])
];
}
$data['pf'] = $this->pf->getprofile(uid());
//$data['edittext'] =
//if(count($data) >= 1){
$this->load->view('wall/v_wall',$data);
I also try the code below but It didn't work.
$r = $this->w->listwall();
foreach ($r as $key => $value) {
$data[] = array($key => $value, $this->w->get_comments($value['p_id']));
}
I have a problem with displaying my data. I have data in the following
filter_name filter_value
Hard Drize Size 16GB
Hard Drize Size 32GB
Screen Size 7''
Screen Size 8''
And I want to present it like this.
Hard Drize Size
16GB
32GB
Screen Size
7''
8''
What I want in my php code is to check if the filter_name is in the $temp array and if it isn't then add it to $temp array so it won't cause duplicate entries. The problem I'm getting now is when I use the same data to do a second foreach inside the loop I get no data and my sql is correct. So I don't know how to out put the values. With the second foreach it only prints out the first $filter_name["filter_name"] and that all.
php:
if($stmt->rowCount() > 0)
{
$filters = "<div class=\"filters\">
<div class=\"apply-filters\">Filters</div>";
$temp = array();
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter_name)
{
if(!in_array($filter_name["filter_name"], $temp))
{
$temp[] = $filter_name["filter_name"];
$filters .= "<div class=\"filter-header\">".$filter_name["filter_name"]."</div>";
//second loop here doesn't work with the same data.
// test if filter_name["filter_name"] == second loop second_loop["filter_name"]
// ten write out second_loop["filter_value"] e.g.
foreach($stmt as $filter_value)
{
if($filter_name["filter_name"] == $filter_value["filter_name"])
{
$filters .= $filter_value["filter_value"] ."<br />";
}
}
}
}
$filters .= "</div>";
}
First, do a var_dump of $stmt before the first and second foreach to look at it's form. Perhaps it's not formatted the way you think?
Why don't you loop over $stmt once and in that loop print $stmt['filter_name'] and $stmt['filter_value']? Now you loop $stmt one "extra" time for each iteration of the first foreach. Instead just do a foreach($stmt as $filter) and $filter, being a associative array, should contain filter_name and filter_value for each entry.
You could then move the actual printing outside of the foreach and only construct your array in the loop that should look something like
array("Hard Drive Size" => array("16GB", "32GB"), "Screen Size" => array("7''", "8''"));
Then you could traverse that data structure using
foreach($myArray as $filter_name => $filter_values)
{
// Print filter name header
foreach($filter_values as $filter_value)
{
// print each value of the specific filter
}
}
To build the presented structure you could do something like
...
$filters = array();
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $filter)
{
$filters[$filter['filter_name']][] = $filter['filter_value'];
}
...
Then iterate the $filters structure and print it.
Update:
From your var_dump of $stmt it's clear that $stmt is not your result set. You should assign the result of $stmt->fetch to something. Like $result = $stmt->fetch(PDO::FETCH_ASSOC) and then iterate over $result.
Check
http://php.net/manual/en/pdostatement.fetch.php
http://php.net/manual/en/pdostatement.fetchall.php
i slightly modified your code to fit your needs:
$temp = array();
foreach($stmt as $filter_name)
{
if(!in_array($filter_name["filter_name"], $temp))
{
echo '<b>' . $filter_name['filter_name'] . '</b><br>';
$temp[] = $filter_name["filter_name"];
foreach($stmt as $filter_value)
{
if($filter_name["filter_name"] == $filter_value["filter_name"])
{
echo $filter_value['filter_value'] . '<br>';
}
}
}
}
you can check a working sample here -> http://codepad.viper-7.com/aFD079
You are missing $ before filter_value.
Change
foreach($stmt as filter_value)
To
foreach($stmt as $filter_value)
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter_name)
may be (i am not sure)
$aaa= $stmt->fetch(PDO::FETCH_ASSOC);
foreach($aaa as $filter_name)
and try
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
$tmp_name='';
$html='';
foreach($rows as $row)
{
if($row['filter_name'] != $tmp_name){
$html .=$row['filter_name'];
}
$html .=$row['filter_value'];
$tmp_name=$row['filter_name'];
}
echo $html;
if($stmt->rowCount() > 0)
{
$filters = "<div class=\"filters\">
<div class=\"apply-filters\">Filters</div>";
$temp = array();
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter)
$temp[$filter['filter_name']][] = $filter['filter_value'];
foreach($temp as $filter_name => $filter_values)
{
$filters .= "<div class=\"filter-header\">".$filter_name."</div>";
foreach ($filter_values as $value)
$filters .= $filter_value."<br />";
}
$filters .= "</div>";
}
I'm relatively new to PHP and I hope you can help me solve my problem. I am selecting out data from a database into an array for timekeeping. Ultimately, I would like to calculate the total number of hours spent on a project for a given customer.
Here is the code to populate a multi-dimensional array:
...
foreach ($record as $data) {
$mArray = array();
$name = $data['user'];
$customer = $data['customer'];
$project = $data['project'];
$hours = $data['hours'];
$mArray[$name][$customer][$project] += $hours;
}
...
I would now like to iterate over $mArray to generate an xml file like this:
...
foreach ($mArray as $username) {
foreach ($mArray[$username] as $customerName) {
foreach ($mArray[$username][$customerName] as $project ) {
echo '<'.$username.'><'.$customerName.'><'.$project.'><hours>'.
$mArray[$username][$customerName][$project].'</hours></'.$project.'>
</'.$customerName.'></'.$username.'>';
}
}
}
This nested foreach doesn't work. Can someone give me a couple of tips on how to traverse this structure? Thank you for reading!
UPDATE:
Based on the comments I've received so far (and THANK YOU TO ALL), I have:
foreach ($mArray as $userKey => $username) {
foreach ($mArray[$userKey] as $customerKey => $customerName) {
foreach ($mArray[$userKey][$customerKey] as $projectKey => $projectName) {
echo '<name>'.$userKey.'</name>';
echo "\n";
echo '<customerName>'.$customerKey.'</customerName>';
echo "\n";
echo '<projectName>'.$projectKey.'</projectName>';
echo "\n";
echo '<hours>'.$mArray[$userKey][$customerKey][$projectKey].'</hours>';
echo "\n";
}
}
}
This is now only providing a single iteration (one row of data).
Foreach syntax is foreach($array as $value). You're trying to use those values as array keys, but they're not values - they're the child arrays. What you want is either:
foreach($mArray as $username) {
foreach($username as ...)
or
foreach($mArray as $key => $user) {
foreach($mArray[$key] as ...)