Looping through a multidimensional array with PHP - php

I'm trying to learn php and talk to an API to retrieve info for my Destiny 2 clan. I've retrieved all the info that I needed and build a new array with the following format:
Array
(
[displayname] => Senaxx
[membershipId] => 4611686018428643772
[characterdetails] => Array
(
[0] => Array
(
[2305843009260824684] => Array
(
[characterlevel] => 30
[light] => 384
[datelastplayed] => 2018-08-19T13:23:27Z
[minutesplayed] => 14901
[racehash] => 898834093
[genderhash] => 3111576190
[emblempath] => /common/destiny2_content/icons/2b6160e0f21e748cd996b404771a850c.jpg
[emblemhash] => 10493725
)
)
[1] => Array
(
[2305843009260824685] => Array
(
[characterlevel] => 30
[light] => 394
[datelastplayed] => 2018-08-18T20:47:09Z
[minutesplayed] => 9647
[racehash] => 2803282938
[genderhash] => 3111576190
[emblempath] => /common/destiny2_content/icons/dcfe74b7a343dd28bd45eee4ea59a1f7.jpg
[emblemhash] => 3860733295
)
)
[2] => Array
(
[2305843009260824686] => Array
(
[characterlevel] => 30
[light] => 394
[datelastplayed] => 2018-08-26T00:15:50Z
[minutesplayed] => 1802
[racehash] => 2803282938
[genderhash] => 3111576190
[emblempath] => /common/destiny2_content/icons/dcfe74b7a343dd28bd45eee4ea59a1f7.jpg
[emblemhash] => 3860733295
)
)
)
)
Array
(
[displayname] => base1981
[membershipId] => 4611686018433367605
[characterdetails] => Array
(
[0] => Array
(
[2305843009265162076] => Array
(
[characterlevel] => 30
[light] => 358
[datelastplayed] => 2018-08-15T11:58:46Z
[minutesplayed] => 13732
[racehash] => 2803282938
[genderhash] => 3111576190
[emblempath] => /common/destiny2_content/icons/9d512efea06e54c1768d434e53510092.jpg
[emblemhash] => 1291068173
)
)
[1] => Array
(
[2305843009265162077] => Array
(
[characterlevel] => 1
[light] => 100
[datelastplayed] => 2017-09-06T14:25:35Z
[minutesplayed] => 0
[racehash] => 898834093
[genderhash] => 2204441813
[emblempath] => /common/destiny2_content/icons/911791e90f955fc637398ea88aba74b7.jpg
[emblemhash] => 1907674137
)
)
[2] => Array
(
[2305843009265162078] => Array
(
[characterlevel] => 30
[light] => 350
[datelastplayed] => 2018-05-27T12:07:38Z
[minutesplayed] => 1658
[racehash] => 3887404748
[genderhash] => 3111576190
[emblempath] => /common/destiny2_content/icons/da0d265bb9e4473c97ba56dc7602ca73.jpg
[emblemhash] => 3941202506
)
)
)
)
These are only 2 player arrays. My whole code has 8. But for this example I think 2 of them will suffice.
My goal is to loop trough the array and retreive all the player info for each displayname.
So i started with which works perfectly:
foreach($claninfo as $clanmember)
{
echo $clanmember['membershipId'];
}
Only grabbing the characterdetails doesn't work for me sadly enough.
The problem for mee seems that there is an extra characterId with an unknown number.
foreach($claninfo as $clanmember)
{
echo $clanmember['membershipId'];
foreach($claninfo->characterdetails as $characterdetails)
{
echo $characterdetails-> light;
}
}
Ultimate goal is to have a table with some of the info in it:
<table>
<tbody>
<tr>
<td>Displayname</td>
<td>Playtime</td>
<td>Character 1</td>
<td>Character 2</td>
<td>Character 3</td>
</tr>
<tr>
<td>Senaxx</td>
<td> </td>
<td>light 384</td>
<td>light 394</td>
<td>light 394</td>
</tr>
<tr>
<td>Base1981</td>
<td> </td>
<td>light 358</td>
<td>light 100</td>
<td>light 350</td>
</tr>
</tbody>
</table>

The associative array key for till the light is:
$claninfo[<some key or index>]['characterdetails'][<Array Index>][<character id>]['light']
So to access light you need to use foreach 3 times:
To get clanmember from claninfo
To iterate $clanmember['characterdetails']
To get rid of character id
foreach($claninfo as $clanmember)
{
echo $clanmember['membershipId'];
foreach($clanmember['characterdetails'] as $characterArray)
{
foreach($characterArray as $characterid => $characterdetails)
{ // You can access $characterid in this block
echo $characterdetails['light'];
}
}
}

characterdetails is an array and not an object.
You can loop through the array using the following code
foreach($claninfo as $clanmember)
{
echo $clanmember['membershipId'];
foreach($claninfo['characterdetails'] as $characterdetails)
{
echo $characterdetails['light'];
}
}

It looks like there are 3 different problems with your code. You are working on arrays, you should not use object notation (->) at all. You use the wrong array in your inner foreach. Third, and this is probably your real question, you need a way to access a key that you don't know (unknown id). That last one can be circumvented for example with array_values (manual). All together:
foreach($claninfo as $clanmember)
{
echo $clanmember['membershipId'];
foreach($clanmember['characterdetails'] as $characterdetails)
{
echo array_values($characterdetails)[0]['light'];
}
}

My final solution was:
foreach($claninfo as $clanmember)
{
echo '<br><b>' . $clanmember['displayname'] . '</b><br>' ;
foreach($clanmember['characterdetails'] as $characterArray)
{
$characterId = $characterArray['characterId'];
$characterlight = $characterArray['light'];
$characterlevel = $characterArray['characterlevel'];
$characterlastplayed = $characterArray['datelastplayed'];
$characterminutesplayed = $characterArray['minutesplayed'];
$characterracehash = $characterArray['racehash'];
$charactergenderhash = $characterArray['genderhash'];
$characteremblempath = $characterArray['emblempath'];
$characteremblemhash = $characterArray['emblemhash'];
echo 'CharacterId: ' . ($characterId) . '<br>';
echo 'Light: ' . ($characterlight) . '<br>';
echo 'level: ' . ($characterlevel) . '<br>';
echo 'Last Played: ' . ($characterlastplayed) . '<br>';
echo 'Minutes Played: ' . ($characterminutesplayed) . '<br>';
echo 'RaceHash: ' . ($characterracehash) . '<br>';
echo 'GenderHash: ' . ($charactergenderhash) . '<br>';
echo 'Emblempath: ' . ($characteremblempath) . '<br>';
echo 'Emblemhash: ' . ($characteremblemhash) . '<br>';
echo '<br>';
}
}

Related

Creating table from multidimention array

I have multidimensional arrays with which I need to make a table in html. I have a problem with matching catalog numbers with dates in the table.
I created an array (little part of it below):
array cotains date => CatalogNo => [catalogNo],[count],[date]
Array
(
[2019/07/19] => Array
(
[71156] => Array
(
[catalogNo] => 71156
[count] => 22
[date] => 2019/07/19
)
[71157] => Array
(
[catalogNo] => 71157
[count] => 21
[date] => 2019/07/19
)
[71221] => Array
(
[catalogNo] => 71221
[count] => 217
[date] => 2019/07/19
)
)
[2019/07/18] => Array
(
[71156] => Array
(
[catalogNo] => 71156
[count] => 26
[date] => 2019/07/18
)
[71157] => Array
(
[catalogNo] => 71157
[count] => 25
[date] => 2019/07/19
)
[71221] => Array
(
[catalogNo] => 71221
[count] => 281
[date] => 2019/07/19
)
[71222] => Array
(
[catalogNo] => 71221
[count] => 173
[date] => 2019/07/19
)
...
I did something like this but this is just bad. I dont know how to do it actually.
$dane_arr <- this is the whole array
<table>
<tr>
<th>CatalogNo</th>
<?php
foreach( $dane_arr as $k => $v )
{
?>
<th><?php echo $k ?></th>
<?php
}
?>
</tr>
<?php
foreach( $dane_arr as $k_date => $date_ )
{
foreach( $date_ as $k_nrArt_ => $nrArt_ )
{ ?>
<tr>
<td><?php echo $nrArt_['catalogNo'] ?></td>
<td><?php echo $nrArt_['count'] ?></td>
</tr>
<?php
}
}
?>
`
There are duplicates in CatalogNo and of course dates doesn't fit.
I want to create table, something like that:
CatalogNo | 2019/07/18 | 2019/07/19 | ...
71156 26 22 ...
71157 25 21 ...
71221 281 217 ...
71222 173 0 ...
(Of course without duplicates in 'CatalogNo')
You would first need to rearrange your array. Then you get all dates, and create the table:
<?php
$catalogUsage = [];
foreach ($dane_arr as $date => $catalogs) {
foreach( $catalogs as $catalogNo => $catalog) {
$catalogUsage[$catalogNo][$date] = $catalog['count'];
}
}
$allDates = array_keys($dane_arr);
?>
<table>
<tr>
<th>CatalogNo</th>
<?php
foreach ($allDates as $date) {
echo "<th>$date</th>"
}
?>
</tr>
<?php
foreach($catalogUsage as $catalogNo => $counts)
{
echo "<tr><td>$catalogNo</td>";
foreach ($allDates as $date) {
echo "<td>" . (isset($counts[$date]) ? $counts[$date] : 0) . "</td>";
}
echo "</tr>";
}
?>
</table>
Code is untested, since I haven't got the original array, so bugs might exist. I just hope this gives you some new inspiration.

Get information out of PHP array in to single values in a loop

SimpleXMLElement Object
(
[deelnemer] => Array
(
[0] => SimpleXMLElement Object
(
[startnummer] => A1
[naam] => Jerry
[adres] => Straat 38
[postcode] => 0000 MC
[woonplaats] => Tilburg
[land] => NED
[geboortedatum] => 27-02-1988
[geslacht] => M
[categorie] => Heren
[onderdeel] => E. 10 Miles - start 15u00
)
[1] => SimpleXMLElement Object
(
[startnummer] => A2
[naam] => Wesley
[adres] => straat 13
[postcode] => 0000 AJ
[woonplaats] => Tilburg
[land] => NED
[geboortedatum] => 20-04-1979
[geslacht] => M
[categorie] => Heren
[onderdeel] => E. 10 Miles - start 15u00
)
)
)
I have this array. I need per 'deelnemer' the individual values.
I tried:
echo '<select>';
foreach ($xml as $obj)
{
foreach ($obj['deelnemer'] as $ob)
{
echo '<option value='.$ob['naam'].'>'.$ob['naam'].'</option>';
}
}
echo '</select>';
But i keep getting error messages. The only thing i can substract atm is 'deelnemer'.
I need a PHP code to create a loop (for each) with a dropdown select with the names of the participants.
$xml is not an array but an object, so in order to access its elements use -> instead of [] as explained in php how to access object array
Try this code:
echo '<select>';
foreach ($xml->deelnemer as $ob) {
echo '<option value="' . $ob->naam . '">' . $ob->naam . '</option>';
}
echo '</select>';

How to use keys to be as indicator?

As I am exploring arrays and how to use it
I encounter this unusual array.
I am trying to achieve this ouput using the array I have posted below.
How can I get this done?
<table>
<tr>
<th>DOGS</th>
<th>CATS</th>
<th>BIRDS</th>
</tr>
<tr>
<td><?php echo $dogs;?></td>
<td><?php echo $cats;?></td>
<td><?php echo $birds;?></td>
</tr>
</table>
Array
(
[cats] => Array
(
[0] => persian
[1] => ragdoll
[2] => siberian
[3] => savannah
)
[dogs] => Array
(
[0] => husky
[1] => bulldog
[2] => beagle
[3] => labrador
)
[birds] => Array
(
[0] => parrot
[1] => owl
[2] => eagle
[3] => love birds
)
)
This is the output I really need to get:
DOGS CATS BIRDS
husky persian parrot
bulldog ragdoll owl
beagle siberian eagle
labrador savannah love birds
You need to loop them first, you cannot outright echo arrays:
$animals = array(
'dogs' => array('husky', 'bulldog', 'beagle', 'labrador'),
'cats' => array('persian', 'ragdoll', 'siberian', 'savannah'),
'birds' => array('parrot', 'owl', 'eagle', 'love birds'),
);
?>
<table cellpadding="10">
<tr><th>DOGS</th><th>CATS</th><th>BIRDS</th></tr>
<?php
$types = array_keys($animals);
for($i = 0; $i < count($animals['cats']); $i++) {
echo '<tr>';
foreach($types as $type) {
echo '<td>' . $animals[$type][$i] . '</td>';
}
echo '</tr>';
}
?>
</table>
Sample Output

Avoid recurring of Records in the code

I am implementing Wordpress feature, viewing posts per Year and Month using PHP as
eg:
Press Releases
2013(4)
October(1)
Announcement1
But I am getting each records as repeated in the result. The code is as shown below:
$query = "SELECT * FROM edu_announcements WHERE status = '1' ORDER BY add_time asc";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
echo '<ul>' . PHP_EOL;
echo '<li><strong>Press releases:</strong></li>' . PHP_EOL;
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['add_time'] ;
$timePeriod =date("F Y", $newDate);
//$timePeriod = date('F Y ',strtotime($newDate));
$timePeriodY = date('Y',$newDate);
$timePeriodM = date('F',$newDate);
if (!isset($newsArray[$timePeriod]))
{
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
$timePeriodY = date('Y',strtotime($timePeriod));
echo '<li><strong>' . $timePeriodY . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//by month
foreach ($newsArray as $timePeriod => $newsItems)
{
echo '<li><strong>' . $timePeriod . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//news items
foreach ($newsItems as $item)
{
echo '<li>';
echo ''.$item["title"].'';
echo '</li>' . PHP_EOL;
}
//end by month
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
//end by year
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
echo '<li> </li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
}
else {
echo 'No announcements';
}
I am getting the result as repeated as shown below:
Array ( [July 2013] => Array ( [0] => Array ( [0] => 99 [id] => 99 [1] => sdfsdf [title] => sdfsdf [2] =>
sdfsdfsdfc
[description] =>
sdfsdfsdfc
[3] => [documents] => [4] => [photo1] => [5] => [photo2] => [6] => [photo3] => [7] => [photo4] => [8] => 1 [public_visibility] => 1 [9] => 0 [dept_visibility] => 0 [10] => 0 [depatment] => 0 [11] => 1373913000 [add_time] => 1373913000 [12] => 1 [status] => 1 [13] => sdfsdf [small_description] => sdfsdf ) [1] => Array ( [0] => 100 [id] => 100 [1] => sefsdfvsxdf [title] => sefsdfvsxdf [2] =>
sdfsdfsd
[description] =>
sdfsdfsd
[3] => [documents] => [4] => [photo1] => [5] => [photo2] => [6] => [photo3] => [7] => [photo4] => [8] => 1 [public_visibility] => 1 [9] => 0 [dept_visibility] => 0 [10] => 0 [depatment] => 0 [11] => 1374604200 [add_time] => 1374604200 [12] => 1 [status] => 1 [13] => sdfsefs [small_description] => sdfsefs ) )
I want distinct records from the table. Can anyone help me to solve this.
If you mean why are you getting the parts of each record duplicated, such as:
[0] => 99
[id] => 99
it is because mysql_fetch_array has a second option (beyond your $resultset), which defaults to int $result_type = MYSQL_BOTH.
The type of array that is to be fetched. It's a constant and can
take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
If you must use the raw (and old) mysql functions (as others say, this is no longer good practice), then you will also want to probably add , MYSQL_ASSOC to the function call, and then deal only with the name of the columns - such as 'id', 'title' & 'description'. There may also be similar parameters to other DB access calls, though mostly they will use the MYSQL_ASSOC-style returns to have the column name by default.
I solved the answer by using the code as shown below:
echo '<div id="news_events_section_wrapper">
<div class="news_events_section">';
$CURRENT_TIMESTAMP=time();
$sqlstr=mysql_query("select * from nesote_edu_announcements where status=1");
$count=mysql_num_rows($sqlstr);
if($count!=0)
{
while($article=mysql_fetch_row($sqlstr))
{
$id=$article[0];
$details= $article[2];
$postedon=date("F j, Y",$article[11]);
$olderpost=date("Y",$article[11]);
$yearnoquery=mysql_query("select count(*) from nesote_edu_announcements where add_time <='$CURRENT_TIMESTAMP' and status=1 ");
$resultq=mysql_fetch_row($yearnoquery);
$numberofposts=$resultq[0];
}
echo "<a href=javascript:showmonths(".$id.") style=".'"'."text-decoration:none".'"><div>';
echo $olderpost;echo '(';echo $numberofposts;echo ')';
echo '</div>
</a>';
$monthqry=mysql_query("SELECT add_time,COUNT(id),id FROM nesote_edu_announcements WHERE status=1 AND (add_time <='$CURRENT_TIMESTAMP') AND FROM_UNIXTIME(add_time, '%Y')='$olderpost' GROUP BY FROM_UNIXTIME(add_time, '%M') ASC");
while($month=mysql_fetch_row($monthqry))
{
$monthsfordisplay=date("F",$month[0]);
$months=date("m",$month[0]);
$monthnos=$month[1];
$artid=$month[2];
echo '<div id='.'"'."month_art".'"'." class=".'"'."month_"; echo $id.'">';
echo '<a href="javascript:showdetails'.'('; echo $artid; echo ')">'; echo $monthsfordisplay;
echo '('; echo $monthnos; echo ')</a></div>';
$smalldisquery=mysql_query("SELECT * FROM nesote_edu_announcements WHERE FROM_UNIXTIME(add_time, '%m')='$months' AND add_time <='$CURRENT_TIMESTAMP' and status=1");
while($smalldisc=mysql_fetch_row($smalldisquery))
{
$articlemonthid=$smalldisc[0];
$disc=$smalldisc[1];
echo ' <div style="display:none;" id="sub_str" class="smalldiscription_';echo $artid; echo '">
<a href='.'"index.php?page=events/announcementdetails/'; echo $articlemonthid; echo '"'.' style='.'"text-decoration:none;'.'">
<font color="#80000">';
$message=substr($disc,0,30);
$message=$message."...";
echo "* ".$message; echo "</font></a>";
echo "</div>";
}
}
}
echo "</div></div>";
This will show announcements in Year-Month basis.

PHP Array and Google Analytics V3 API

I am using the Google Analytics V3 PHP OAuht API. When using Simple.php in Google Analytics API Example the data are returned as PHP arrays. I am using the following call to get a more detailed answer to some specific data. It works fine.
$ids = "ga:xxxxxx";
$start_date = "2011-01-01";
$end_date = "2011-11-30";
$metrics = "ga:visits,ga:pageviews";
$dimensions = "ga:browser";
$optParams = array('dimensions' => $dimensions);
$data = $service->data_ga->get($ids,$start_date,$end_date,$metrics,$optParams);
Output of the Array is
Data
Array
(
[kind] => analytics#gaData
[id] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxxxx&dimensions=ga:browser&metrics=ga:visits,ga:pageviews&start-date=2011-01-01&end-date=2011-11-30&start-index=1&max-results=1000
[query] => Array
(
[start-date] => 2011-01-01
[end-date] => 2011-11-30
[ids] => ga:xxxxxxxx
[dimensions] => ga:browser
[metrics] => Array
(
[0] => ga:visits
[1] => ga:pageviews
)
[start-index] => 1
[max-results] => 1000
)
[itemsPerPage] => 1000
[totalResults] => 220
[selfLink] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxx&dimensions=ga:browser&metrics=ga:visits,ga:pageviews&start-date=2011-01-01&end-date=2011-11-30&start-index=1&max-results=1000
[profileInfo] => Array
(
[profileId] => xxxxx
[accountId] => xxxxx
[webPropertyId] => UA-xxxxxx-x
[internalWebPropertyId] => xxxxxxxxxx
[profileName] => xxxxx.com
[tableId] => ga:xxxxxxxx
)
[containsSampledData] =>
[columnHeaders] => Array
(
[0] => Array
(
[name] => ga:browser
[columnType] => DIMENSION
[dataType] => STRING
)
[1] => Array
(
[name] => ga:visits
[columnType] => METRIC
[dataType] => INTEGER
)
[2] => Array
(
[name] => ga:pageviews
[columnType] => METRIC
[dataType] => INTEGER
)
)
[totalsForAllResults] => Array
(
[ga:visits] => 36197
[ga:pageviews] => 123000
)
[rows] => Array
(
[0] => Array
(
[0] => (not set)
[1] => 459
[2] => 1237
)
[1] => Array
(
[0] => 12345
[1] => 3
[2] => 3
)
[2] => Array
(
[0] => 440955
[1] => 1
[2] => 1
)
[3] => Array
(
[0] => Alexa Toolbar
[1] => 1
[2] => 1
)
[4] => Array
(
[0] => Android Browser
[1] => 4177
[2] => 9896
)
....
The [Rows] Array has 219 entries.
Now the problem. I have spent the last week trying to parse this into an HTML table or anything that looks presentable. I have come close, but it seems this multi-dimensional array is beyond what I am able to handle. I am also trying to keep the solution flexible enough to handle more metrics or dimensions if they are added as well. I am self-taught PHP, so maybe I am missing a function or two that could make this easier. Thanks again for any hints, tips of ideas to make this work.
I got a bit further, but I does not fully format the way I want...maybe someone can see where I went wrong
$output = $service->data_ga->get($ids,$start_date,$end_date,$metrics,$optParams);
echo'<table style="text-align: left; width: 100%;" border="1" cellpadding="2"
cellspacing="2">
<tbody><tr>';
foreach ($output['columnHeaders'] as $header) {
print "<td>";
printf('%25s', $header['name']);
print "</td>";
}
print "</tr>";
foreach ($output['rows'] as $row) {
print "<td>";
foreach ($row as $column)
printf('%25s', $column);
print "</td>";
}
print "\n";
echo'
</tbody>
</table>';
I still can't seem to get the rows to display right.
To get you on your way use
$data [rows][$i][$j][columnHeaders] [0][name]
$data [rows][$i][$j][columnHeaders] [1][name]
and for rows use something like
$data [rows][0][1]
You will have to get the variable via increment with something like:
var =(count($data [columnHeaders]));
for ($i='0'; $i<=$var; $i++) {
echo '.$data [columnHeaders] [$i][name].';}
This should get you on your way towards building your table. Good Luck!
The issue is in your foreach for the table body rows. You appear to have missed the rows out. Wrap it in another loop to print out tr around the set of tds.
This is what I used for printing out a table of analytics data:
$data = $analytics->data_ga->get('ga:' . $profileId, $dateFrom, $dateTo, $metrics, array('dimensions' => $dimensions));
<table>
<thead>
<tr>
<?php
foreach ($data->columnHeaders as $header) {
$headerName = ucwords(preg_replace('/(\w+)([A-Z])/U', '\\1 \\2', str_replace('ga:', '', $header->name)));
print '<th>';
printf('%s', $headerName);
print '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
foreach ($data->rows as $row) {
print '<tr>';
foreach ($row as $cell) {
print '<td>';
printf('%s', $cell);
print '</td>';
}
print '</tr>';
}
?>
</tbody>
</table>

Categories