Display two arrays in the same table - php

$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.

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

I need a counter within a counter

I have searched for this, can't find it and it should be simple, but now I'm crosseyed. Forgive me - I've only been at this for a few months.
I need a counter within a counter in php, such that I pair $Id1 with $Id2, then $Id3, then $Id4, etc. for a single loop through, and then for the second loop pair $Id2 with $Id3, then $Id4, then $Id5 etc. I get the Ids from a sql query, then I use both of them to run a calculation of their relationship, but first I just need the structure to run these two loops, one within the other. Thanks for any help and your patience.
Edited to add what I have so far:
$collection = [];
$sql = 'SELECT id, name FROM table';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$collection[] = $row;
}
$ct = count($collection);
for ($i = 0; $i < $ct; $i++)
{
$Id1 = $collection[$i]['id'];
for ($j = 0; $j < $ct; $j++)
{
$Id2 = $collection[$j]['id'];
if($Id1 != $Id2){
echo 'IDs: ' . $Id1 . ' ' . $Id2 . '<br>';
}
}
}
}
If you fetch the IDs from your query into an array like this: $ids = [1,2,3,4,5,6,7,8];, you can get a list of pairs using array_chunk, then shifting off the first element, and repeating this process until the array is empty.
while ($ids) { // repeat until empty
$pairs = array_chunk($ids, 2); // split into pairs
foreach ($pairs as $pair) {
if (count($pair) == 2) { // verify that you have a pair (last element will
// have only one item when count($ids) is odd)
var_dump($pair); // do something with your pair of IDs
}
}
$remove_first = array_shift($ids); // shift off the first ID
}
Please note that using array_shift like this will destroy your input array, so if you need to do something else with it as well, make a copy of it before using this approach.

Issue with getting data when traversing through an array PHP with a variable

I asked a similar question earlier but I couldn't get a clear answer to my issue. I have a function "isParent" that gets 2 pieces of data. Each 1 of the 2 gets a string separating each value with a , or it just gets a plain int and then checks if the first value given is a parent of the second.
I pull the 2 bits of data in and explode them but when I go through my nested for loop and try to test
$toss = $arr1[$i];
print_r($toss);
It comes up blank. I have no idea what the issue is: Here is the full code of the function...
function isParent($parent, $child)
{
$parentArr = explode(',', $parent);
$childArr = explode(',',$child);
//Explode by Comma here. If array length of EITHER parentArr or childArr > 1 Then throw to an Else
if(count($parentArr) <= 1 && count($childArr) <= 1) //If explode of either is > 1 then ELSE
{
$loop = get_highest_slot(15);
for($i = $loop; $i > 0; $i--)
{
$temp = get_membership_from_slot($i,'id_parent','id_child');
if($temp['id_parent'] == $parent && $temp['id_child'] == $child)
{
return 1;
}
}
}
else //set up a for loop in here so that you traverse each parentArr value and for each iteration check all child values
{
$i = count($parentArr);
$c = count($childArr);
for(;$i >=0;$i--) //Loop through every parent
{
for(;$c >=0;$c--)
{
echo '<br>$i = ';
print_r($i);
echo '<br><br>Parent Arr at $i:';
$toss = $parentArr[$i];
echo $toss;
echo '<br>';
print_r($childArr);
echo '<br><br>';
if(isParent($parentArr[$i],$childArr[$c])) //THIS CAUSES AN INFINITE YES! Learn how to pull an array from slot
{
return 1;
}
}
}
}
return 0;
}
You are missing some code for the slot procedures. Apart from that, you probably need to use a different variable for the inner for loop. because $c will be 0 after the first iteration of $i.
Thanks for the help! The issue was in the recursive call back to the top of the function. It was tossed empty slots and when comparing 2 empty slots it returned a false positive. A quick !empty() check fixed it.

php arrays and mysql query

This is driving me nuts! I need to fill up and HTML table with values that I pulled out from a DB.
The HTML table has 100 one td for each value.
I have an array that I populate doing this:
$x = 1;
$ArrayA = array();
for ($x = 1; $x <= 100; $x++) {
$ArrayA[$x] = 0;
}
So now I have an array with 100 values, right?
Then I query my DB, and get the result that I "want"
(select num from table1)
6 rows with the following values:
1,3,14,50,100.
Then I insert the values from my query into the $ArrayA that I populated before with one hundred 0's
$x = 1;
while ($row = mysql_fetch_array($result))
{
extract($row);
$ArrayA[$x] = "$num";
$x++;
}
Now $ArrayA has this:
1,3,14,17,100,0,0,0,0,0,0,0,0,0,0,0,0.....
And my goal is to replace with a 0 where I should have a "next" number, hard to explain..
I need this result:
1,0,3,0,0,0,0,0,0,0,0,0,0,14,0,0,17,0....
I tried to use PHP array_splice, but it did not work.
I tried with some if statements but my logic and programing experience is not that good.
Any suggestions?
Thanks
If i understand this right, you want to add a zero after every element returned by your query? Right? If so, why not add a zero right after you add an element into the array?
$x = 1; while ($row = mysql_fetch_array($result)) {
extract($row);
$ArrayA[$x] = "$num";
$x++;
$ArrayA[$x] = "0"; //adds zero after every $num insert
}
Maybe you can clarify if this isn't what you're asking...
$match_rows = mysql_fetch_array($result);
$rows = range(1,100);
foreach( $rows as $row){
echo '<td>';
if( in_array($row, $match_rows) ){
echo $row;
}else{
echo 0;
}
echo '</td>' . PHP_EOL;
}
Sorry, that is untested - it could be shorter or neater, but like that possibly illustrates another way of achieving what you want.
I think this is what you want for your second code block:
while ($row = mysql_fetch_array($result))
{
extract($row);
if($num > 0 && $ <= 100 )
{
$ArrayA[$num] = "$num";
}
}
If your DB values are 3, 10, 15, 22, 100, you'd end up with 0,0,3,0,0,0,0,0,0,10,0,0,0,0,15, etc etc.

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