Counting values in the same level of a multidemensional array - php

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

Related

Group same date and count together

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

Display two arrays in the same table

$row = $query->fetchAll(PDO::FETCH_ASSOC);
$num_rows = count($row);
for ($i = 0; $i < $num_rows; $i++)
{
$title = htmlspecialchars($row[$i]['title']);
$author =htmlspecialchars($row[$i]['author']);
$school =htmlspecialchars($row[$i]['school']);
$solution = $row[$i]['solution'];
$notes = $row[$i]['notes'];
$ad = array($title, $price, $author, $school, $contact, $content, $date);
$inlcude = array($solutions, $notes);
$field = 0;
echo "<table border='1'>";
// foreach($inlcude as $in) This failled miserably
foreach ($ad as $post)
{
if ($field < 3) //The first three values are placed in the first row
{
echo "<td>$post</td>";
}
if ($field >= 3)
{
echo "<tr><td>$post</td><td>$in</td></tr>";
}
$field++;
}
echo '</table>';
}
I have two arrays and I would like to display them in different columns in my table. $ad displays perfectly fine but I'm having trouble displaying the contents in $inlcude in the second column. I've tried putting another foreach loop to iterate through contents of the second array but that really screws up my table by placing random values in different places on the table. Besides the foreach loop, I don't know of any other way to iterate through the array. Any suggestions would be appreciated.Thanks!
I want the graph to look like this where $p=$post and $i=$in. Moreover, three columns in first row and two columns in every row after that
$p $p $p
$p $i
$p $i
Assuming that your arrays are formatted correctly, you probably want to use array_shift(). Try something like this:
// Start by copying the $include array, because array_shift() is a destructive
// operation and you might want to use $includes again.
$includes_copy = $include;
// Start with your leading <tr> cell.
echo "<tr>";
// Now loop your ad array.
foreach ($ad as $post) {
//The first three values are placed in the first row.
if ($field < 3) {
echo "<td>$post</td>";
$field++;
}
if ($field == 3) {
echo "</tr>"; // Closing tags are good form.
}
if ($field >= 3) {
// Using array_shift() will return the first element from the array.
// The returned element will be removed from the array.
$in = array_shift($includes_copy);
// $post is populated from foreach(), $in is populated by array_shift().
echo "<tr><td>$post</td><td>$in</td><td></td></tr>";
$field += 3;
}
}
Basically, the concept is that foreach($array as $val) is logically equivalent to while($val = array_shift($array)), meaning that you can run two foreach() at the same time. The only difference is that array_shift() is destructive.

Create multiple span based on array

I have an array that looks like this:
$elm = 'a,b,c';
I need the values of the array so I use explode to get to them:
$q = explode(",",$elm);
I then would like to echo every single item into a span, so I make an array:
$arr = array();
foreach($html->find($q[0]) as $a) {
$arr[] = $a->outertext;
}
$arr2 = array();
foreach($html->find($q[1]) as $b) {
$arr2[] = $b->outertext;
}
$arr3 = array();
foreach($html->find($q[2]) as $c) {
$arr3[] = $c->outertext;
}
And then finally I output like this:
echo "<ul>";
for($i=0; $i<sizeof($arr + $arr2 + $arr3); $i++)
{
echo "<li>";
echo "<span>".$arr[$i]."</span>";
echo "<span>".$arr2[$i]."</span>";
echo "<span>".$arr3[$i]."</span>";
echo "</li>";
}
echo "</ul>";
The problem is that I have to write all the items ($q[0] + $q[1] + $q[2]) and the corresponding span (<span>".$arr[$i]."</span>) This is a problem because in reality I don't know what and how long the first array ($elm) is. Therefore I don't want to 'physically' write down all the span elements but rather create them on the fly depending on the array $elm. I tried many things but I can't figure it out.
The basic issue here is that you don't know how many elements $elm will contain. foreach is the best choice here, as it doesn't require the length of the array to loop through it.
Use a nested foreach loop to store all the outertexts in an array:
foreach (explode(",", $elm) as $elem) {
foreach ($html->find($elem) as $a) {
$arr[$elem][] = $a->outertext;
}
}
$arr[$elem][] is the important bit here. On each iteration of the outer loop, the value of $elem will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a'], $arr['b'] and $arr['c'] and add the outertext values to the respective index.
Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:
echo "<ul>";
foreach ($arr as $sub) {
echo "<li>";
foreach ($sub as $span) {
echo "<span>".$span."</span>";
}
echo "</li>";
}
echo "</ul>";

PHP build array from variables

So I have a variable which I explode:
$values = explode ('|', $split);
This can contain any number of values from 1 to 10+
I have another big array let's call it $tree. I need to loop round the $values whilst building up an array based on the $tree variable.
E.g:
$newArray = $tree [$values [0]][$values [1]];
But this needs to be done dynamically based on the number of elements in the $values array.
Any ideas?
Thanks
Is this what you're trying to do?
$newArray = array();
foreach($values as $key => $val)
{
$newArray[] = $tree[$val][$values[$key + 1]];
}
You need a foreach loop that goes to every single value you have and then put them in the $tree array something like:
$newArray = array();
foreach($values as $index => $value)
{
$newArray[] = $tree[$value][$value[$index + 1]];
}
create a temporary array from $tree and iterate through the values getting each index:
$result = $tree;
foreach ($values as $val){
$result = $result[$val];
}
This way you go down one level deeper into $tree with each value supplied in $values, and $result holds the value stored in $tree at the point you have reached. For example if you have a navigation tree, $values would be the "breadcrumb" of the current navigation position, and $result is the remaining tree from this point downwards.
I think this is what you want. It goes through pairs of elements of $values, using them as the indexes into $tree to add to $newArray
$newArray = array();
for ($i = 0; $i < count(values); $i += 2) {
$newArray[] = $tree[$values[$i]][$values[$i+1]];
}
$values=array(0, 1, 3);
$tree=array("First", "Second", "Third", "Fourth");
$newarray=array();
for ($i=0; $i<count($values); $i++)
{
$newarray[]=$tree[$values[$i]];
}
echo(implode($newarray,", "));
Something like that what you were looking for?

Limit a multidimensional array response

Having 3 multidimensional arrays, to whom I do a foreach how can I limit the multidimensional response inside foreach from X items to lets say 20.
Code:
$i = 0;
foreach ($value->channel->item as $item)
{
$data['data'][$keySection]['item1'][$i]['url'] = $item->url;
$data['data'][$keySection]['item1'][$i]['title'] = $item->title;
$data['data'][$keySection]['item1'][$i]['img'] = $item->thumb;
$i++;
}
where $value is contained within
foreach ($homeData as $keySection => $valueSection)
{
foreach($valueSection as $key => $value)
{
switch ($key)
{
I've tried aplying some fors both within foreach ($value->channel->item as $item) as outside but I just can't get it to work properly, I get either doubled results or not working at all.
How can I make this work??
Edit:
$i has nothing to do with it... I need to limit $value->channel->item where item contains X results
Edit2:
$i is for $homeData where $homeData contains three values and each and one of those will later contain 3 different values of $value->channel->item so if item contains 20 results, will be 3x20 = 60 and $i is ment to separate each 20 results...
Edit3:
ok, now I get it... sorry for the misunderstanding
After you start the foreach, add:
if($i > 19) {
break;
}
This checks if $i is greater than 19 (which means 20 iterations) and then breaks this foreach loop. More information about break, here.
You can do it like :
$i = 0;
foreach ($value->channel->item as $item)
{
if($i > 19) {
break;
}
$data['data'][$keySection]['item1'][$i]['url'] = $item->url;
$data['data'][$keySection]['item1'][$i]['title'] = $item->title;
$data['data'][$keySection]['item1'][$i]['img'] = $item->thumb;
$i++;
}
This will give you 20 items.
Hope this is what you want :)

Categories