Group same date and count together - php

I have done a code to call an array of a value based on each date. My code is below:
$matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
$array[] = [];
foreach ($matchs as $key => $match) {
$array[$match->date_access] = $match->status;
}
dd($array);
Using this I try and dd(); I get output like this:
What I'm trying to do now is to first group the same dates together and also I want to then count the total for that dates. how can I do this?

Not sure what you mean with "date". But if you mean the same day it would be this:
$matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
$array[] = [];
foreach ($matchs as $key => $match) {
$day = substr($match->date_access, 0, 10);
if(isset($array[$day])){
$array[$day]++;
}else{
$array[$day] = 1;
}
}
dd($array);

$array= array();
$arrayCount=array();
foreach ($matchs as $key => $match) {
$time = strtotime($match->date_access);
$newformat = date('Y-m-d',$time);
if(!array_key_exists($newformat , $array)){
$i=1;
$array[$newformat]=$match->status;
}
//$array[$newformat]=$i; remove this comment if you want the count inside
$arrayCount[$newformat]=$i;
$i++;
}
in the event you want to maintain the "match" value in your array if not just un-comment the code and remover $arrayCount occurrences

Related

Counting values in the same level of a multidemensional array

I'm trying to count how many of the same calendar weeks I have inside the same level of a multidimensional array. My start array can be seen on the picture on the left part, my output is composed of an ID [0] and the rest are the dates corresponding to that ID.
On my code I convert these dates to calendar weeks and then try to count them with a foreach loop and then unset the last values if they are identical to the newest ones, so that I only have the final count. My Problem is that as you can see on the last array [1975]->1->1 the count is not right, it is taking in count also the same weeks from the other ID.
Any kind of help is much appreciated!
My code looks like this:
$array= array();
$arrayCount=array();
$j=0;
foreach ($sorted as $value) {
$k=1;
foreach ($value[1] as $match) {
$time = strtotime($match);
$Calendar_Week = date('W',$time);
$Year = date('Y',$time);
if(!array_key_exists($Calendar_Week , $array)){
$i=1;
$array[$Calendar_Week][$j]=$match;
}
$arrayCount[$sorted[$j][0]][1][0]=$sorted[$j][0];
$arrayCount[$sorted[$j][0]][1][$k][]=$i;
$arrayCount[$sorted[$j][0]][1][$k][]=$Calendar_Week;
$arrayCount[$sorted[$j][0]][1][$k][]=$Year;
// Delete previous counts of the same value
if ($arrayCount[$sorted[$j][0]][1][$k-1][1]==$Calendar_Week & $arrayCount[$sorted[$j][0]][1][$k-1][2]==$Year) {
unset($arrayCount[$sorted[$j][0]][1][$k-1]);
}
$i++;
$k++;
}
$j++;
}
dd($sorted, $arrayCount);
You just need to reset the $i and $array inside the foreach loop
$i=1;
$array = array();
Please check this code
$array= array();
$arrayCount=array();
$j=0;
foreach ($sorted as $value) {
$k=1;
$i=1;
$array = array();
foreach ($value[1] as $match) {
$time = strtotime($match);
$Calendar_Week = date('W',$time);
$Year = date('Y',$time);
if(!array_key_exists($Calendar_Week , $array)){
$i=1;
$array[$Calendar_Week][$j]=$match;
}
$arrayCount[$sorted[$j][0]][1][0]=$sorted[$j][0];
$arrayCount[$sorted[$j][0]][1][$k][]=$i;
$arrayCount[$sorted[$j][0]][1][$k][]=$Calendar_Week;
$arrayCount[$sorted[$j][0]][1][$k][]=$Year;
// Delete previous counts of the same value
if ($arrayCount[$sorted[$j][0]][1][$k-1][1]==$Calendar_Week & $arrayCount[$sorted[$j][0]][1][$k-1][2]==$Year) {
unset($arrayCount[$sorted[$j][0]][1][$k-1]);
}
$i++;
$k++;
}
$j++;
}
dd($sorted, $arrayCount);

Retrieve Highest Value from Array in PHP

I would post the entire code, but it is lengthly and confusing, so I'll keep it short and simple. This is complicated for myself, so any help will be greatly appreciated!
These are the values from my Array:
Light Blue1
Blue2
Blue1
Black3
Black2
Black1
The values I need to retrieve from my Array are "Light Blue1", "Blue2" and "Black3". These are the "highest values" for each color.
Something similar to what I'm looking for is array_unique, but that wouldn't work here. So something along those lines that can retrieve each color with its highest number.
Thanks!
Assuming your format is always NameNumber a regex should do the trick for separating the data. This will loop through your data in the order your provide and grab the first element that is different and put it into $vals. I am also assuming your data will always be ordered as your example shows
$data = ['Light Blue1',
'Blue2',
'Blue1',
'Black3',
'Black2',
'Black1'];
$vals = [];
$current = '';
foreach($data as $row) {
if(!preg_match('/(.*)(\d)/i', $row, $matched)) continue;
if($matched[1] != $current) {
$vals[] = $row;
$current = $matched[1];
}
}
The solution using preg_split and max functions:
$colors = ['Light Blue1', 'Blue2', 'Blue1', 'Black3', 'Black2', 'Black1'];
$unique_colors = $result = [];
foreach ($colors as $k => $v) {
$parts = preg_split("/(\d+)/", $v, 0, PREG_SPLIT_DELIM_CAPTURE);
$unique_colors[$parts[0]][] = (int) $parts[1];
}
foreach ($unique_colors as $k => $v) {
$result[] = $k . max($v);
}
print_r($result);
The output:
Array
(
[0] => Light Blue1
[1] => Blue2
[2] => Black3
)
If you pre-sort your array with "natural sorting", then you can loop through the array and unconditionally push values into the result with digitally-trimmed keys. This will effectively overwrite color entries with lesser number values and only store the the highest numbered color when the loop finishes.
Code: (Demo)
natsort($data);
$result = [];
foreach ($data as $value) {
$result[rtrim($value, '0..9')] = $value;
}
var_export(array_values($result));
Or you could parse each string and compare the number against its cached number (if encountered before): (Demo)
$result = [];
foreach ($data as $value) {
sscanf($value, '%[^0-9]%d', $color, $number);
if (!isset($result[$color]) || $result[$color]['number'] < $number) {
$result[$color] = ['value' => $value, 'number' => $number];
}
}
var_export(array_column($result, 'value'));
A related technique to find the highest value in a group

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

error on second foreach loop in php

i have an array containing query results to wordpress db:
$query = $wpdb->get_results("SELECT id, user_login, date, data1, data2 FROM table WHERE date >= 'date1' AND date <= 'date2'");
foreach ($query as $a) {
$array[] = array('id'=>$a->id, 'user_login'=>$a->user_login, 'date'=>$a->date, 'data1'=>$a->data1, 'data2'=>$a->data2);
}
next foreach loop to make strings for my needs i'm getting nothing, even
foreach ($array as $c) {
$d = $c->id;
}
echo $d;
returns Null. what am i doing wrong ?
$c is an array not an object.
Try $d = $c["id"];
Wrong
$d = $c->id;
Right
$d = $c["id"];

What is the best way to generate a condensed array like this in PHP?

I have an array like:
$arr[0] = ("1-3-2011","1","15"); //date(dd-mm-yyyy),id,amt
$arr[1] = ("1-4-2011","2","5");
$arr[2] = ("12-3-2011","6","20");
$arr[3] = ("1-3-2011","10","10");
$arr[4] = ("12-3-2011","3","10");
$arr[5] = ("1-4-2011","5","15");
$arr[6] = ("1-3-2011","7","15");
From this I need to generate a condensed array like
$newarr[0] = ("1-3-2011","1,7,10","40");
$newarr[0] = ("1-4-2011","2,5","20");
..
...
Basically the first one is a multidimentional array, containing date,id, and amount. In the new array, I need to condense the previous one for each unique date, ids as a csv string for duplicate dates, and amounts added.
What's the most efficient way to do this, performance wise?
Something like this should do it:
$newarr = array();
foreach($arr as $row) {
if(!isset($newarr[$row[0]])) {
$newarr[$row[0]] = array('ids' => array(), 'amount' => 0);
}
$newarr[$row[0]]['ids'][] = $row[1];
$newarr[$row[0]]['amount'] += $row[2];
}
foreach($newarr as $key => &$row) {
$row = array($key, implode(',', $row['ids']), $row['amount']);
} unset($row);
Working example:
http://codepad.org/UmiDKLYJ

Categories