I have an array with fetched data from a database query:
Array
(
[0] => stdClass Object
(
[dataid] => 925977
[camp_id] => 2003001
[cid] =>
[userid] => ushio12
[ip_client] => 36.74.213.75
[register_time] => 2015-04-01 22:39:04
[country] => Indonesia
[game_name] => TOUCH
[server] => SALSA
[nominal] => Rp 100000
[logintime] => 2015-04-01 22:39:12
)
//...
[2] => stdClass Object
(
[dataid] => 929703
[camp_id] => 2003001
[cid] =>
[userid] => fiqri179
[ip_client] => 125.162.70.16
[register_time] => 2015-04-02 23:40:23
[country] => Indonesia
[game_name] => TOUCH
[server] => K-POP
[nominal] => Rp 100000
[logintime] => 2015-04-02 23:40:26
)
)
So far, based on the array result above, I fetch the data in view manually like this:
<tr>
<th>dataid</td>
<th>camp_id</td>
<th>cid</td>
<th>ip_client</td>
<th>register_time</td>
<th>country</td>
<th>game_name</th>
<th>server</th>
</tr>
<?php
if(isset($result))
{
foreach ($result as $row)
{
echo "<tr>";
echo "<td>".$row->dataid."</td>";
echo "<td>".$row->camp_id."</td>";
echo "<td>".$row->cid."</td>";
echo "<td>".$row->ip_client."</td>";
echo "<td>".$row->register_time."</td>";
echo "<td>".$row->country."</td>";
echo "<td>".$row->game_name."</td>";
echo "<td>".$row->server."</td>";
echo "</tr>";
}
}
?>
It is because I know what info the user will search.
However, this time, I don't know what the user will search (Which columns gets returned). They may search only some specific info or whole info, so that the array result will have less or other columns that this one now.
So my question is, how to automatically generate the view based on the keys (column names) array the user try to search, so that the <th>".$key."</th> will be dynamic?
This should work for you:
Here I just cast the first stdClass in the array with index 0 to an array, that then I can grab all keys with array_keys().
<?php
$columns = array_keys((array)$result[0]);
echo "<tr>";
foreach($columns as $column)
echo "<th>$column</th>";
echo "</tr>";
?>
EDIT:
With the rows you do the same like this:
foreach ($result as $row) {
echo "<tr>";
foreach($columns as $column)
echo "<td>" . $row->$column . "</td>";
echo "</tr>";
}
Related
I want to retrieve a single value from this php array.
My array in PHP is:
Array
(
[0] => stdClass Object
(
[id] => 27
[id_customer] => 19
[my_cart] => Array
(
[c81e728d9d4c2f636f067f89cc14862c] => Array
(
[id] => 2
[qty] => 1
[price] => 39000
[name] => HEBERGEMENT WEB MUTUALISE PREMIUM
[rowid] => c81e728d9d4c2f636f067f89cc14862c
[subtotal] => 39000
)
[a87ff679a2f3e71d9181a67b7542122c] => Array
(
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
)
1
[created_at] => 2020-03-30
)
)
The problem is that I can not get qty, name, price
I tried by doing this in my foreach
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
foreach($data as $s){
echo 'My cart: '.$s;
}
}
}
But nothing is happened! I want to get price, name and qty.
In this line:
echo 'My cart: '.$s;
The variable $s holds an array, not a string. If you follow your data structure, the contents of $s would be similar to this:
Array (
[id] => 4
[qty] => 1
[price] => 150000
[name] => HEBERGEMENT WEB MUTUALISE ULTIMATE
[rowid] => a87ff679a2f3e71d9181a67b7542122c
[subtotal] => 150000
)
So, in order to get name, qty, price, you'd need to change your inner loop to something like this:
foreach ($data as $s) {
echo 'Product name: ' . $s['name'] . '<br>';
echo 'Quantity: ' . $s['qty'] . '<br>';
echo 'Price: ' . $s['price'] . '<br>';
}
What happens when you try to use an array as a string is that it shows up as the string "Array" and will trigger a PHP Notice: Array to string conversion in [location]. I'm guessing this error might be the reason you get nothing, instead of My cart: Array.
To get several keys from my_cart array, try to write the loop like this :
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = $cd->my_cart;
if(is_array($data)){
$filtered = [];
$keys = ['qty', 'name', 'price']; // the keys
$column_keys = array_flip($keys); // getting keys as values
foreach ($data as $key => $val) {
// getting only those key value pairs, which matches $column_keys
$item = array_intersect_key($val, $column_keys);
if (!empty($item))
$filtered[$key] = $item;
}
echo 'My cart: <br/>';
print_r($filtered);
}
}
I found the solution. When inserting into database I encode it like this htmlspecialchars(json_encode($data)) and decode in with json_decode while getting the $data. So now I have this:
foreach($cart_data as $cd){
echo 'ID Table: '.$cd->id.'<br>';
echo 'ID customer: '.$cd->id_customer.'<br>';
$data = json_decode($cd->my_cart);
foreach($data as $row){
echo $row->name;
echo $row->qty;
echo $row->price;
}
}
This question already has answers here:
Looping a multidimensional array in php
(3 answers)
Closed last year.
Here is an array from which I need to sort out the dept name, the full name and the salary , whose salary are above 10000rs.
The array is:
Array
(
[PHP] => Array
(
[0] => Array
(
[name] => Jay
[salary] => 8000
)
[1] => Array
(
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[name] => Mihir
[salary] => 12000
)
)
[Flex] => Array
(
[0] => Array
(
[name] => Vijay
[salary] => 14000
)
)
[System] => Array
(
[0] => Array
(
[name] => Kishan
[salary] => 5000
)
)
)
I am totally confused inside the loops of foreach and don't know how to call each value from the array.
My code allows me to display only names.
Can i know what is the best way to print and work with multidimensional arrays in PHP.
My code:
foreach($newArray as $x=>$x_value){
foreach ($x_value as $y=> $y_value){
if($y_value['salary']>10000)
echo $y_value['name']." has ". $y_value['salary']. ", ";
}
}
Use the following, Tested and working
$filterArray = array();
$i = 0;
foreach($salary as $dept => $employee){
foreach($employee as $index => $data){
if($data['salary'] > 10000){
$filterArray[$i]['deprtment'] = $dept;
$filterArray[$i]['name'] = $data['name'];
$filterArray[$i]['salary'] = $data['salary'];
}
$i++;
}
}
Result :-
Array
(
[1] => Array
(
[deprtment] => PHP
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[deprtment] => PHP
[name] => Mihir
[salary] => 12000
)
[3] => Array
(
[deprtment] => Flex
[name] => Vijay
[salary] => 14000
)
)
Your input is nested array. So you have to use foreach +for loop:
$final_array = array();
foreach($newArray as $x=>$x_value)
{
foreach ($i=0;$i<count($x_value);$i++)
{
if($x_value[$i]['salary']>10000)
{
if(isset($final_array[$x]))
{
array_push($final_array[$x],array("name"=>$x_value[$i]['name'],"salary"=>$x_value[$i]['salary']));
}
else
{
$final_array[$x] = array();
array_push($final_array[$x],array("name"=>$x_value[$i]['name'],"salary"=>$x_value[$i]['salary']));
}
}
}
}
$final_array print dep wise name & salary which is max than 10000
Output :
Array
(
[PHP] => Array
(
[0]=> Array
(
[name] => Raj
[salary] => 15000
)
[1]=> Array
(
[name] => Mihir
[salary] => 12000
)
)
[Flex] => Array
(
[0]=> Array
(
[name] => Vijay
[salary] => 14000)
)
)
)
Here is a simpler solution for looping over the arrays.
foreach ($bigArray as $department => $employees) {
foreach ($employees as $employee) {
if ($employee["salary"] > 10000) {
echo "Department: " . $department;
echo "Employee: " . $employee;
echo "Salary: " . $salary;
} else {
echo $person . " has no money.";
}
}
}
This will output what you were trying to print in your example.
Output for the first employee:
Department: <department name>
Employee: Raj
Salary: 15000
In the future, you should include the department names in your example array since your example doesn't have all of the information you are trying to print; we can't print something that doesn't exist.
I don't know, if i've got you correctly, but if you need to filter out all the people from the sub-arrays (PHP, Flex, System, ...) and then sort them either by their name or salary, you could do it in this or a similar way:
$array = [
'PHP' => [
[
'name' => 'Jay',
'salary' => 8000
],
[
'name' => 'Raj',
'salary' => 15000
],
[
'name' => 'Mihir',
'salary' => 12000
]
],
'Flex' => [
[
'name' => 'Vijay',
'salary' => 14000
]
],
'System' => [
[
'name' => 'Kishan',
'salary' => 5000
]
]
];
$array_people = [];
$array_sorted = [];
$sort_by = 'name'; // Array key name
$sort_desc = false;
$min_salary = 10000;
foreach ($array as $type => $people)
{
foreach ($people as $info)
{
if ($info['salary'] >= $min_salary) {
$array_sorted[] = $info[$sort_by];
$array_people[] = $info;
}
}
}
if ($sort_desc) {
// Sort descending
arsort($array_sorted);
} else {
// Sort ascending
asort($array_sorted);
}
$array_final = [];
foreach (array_keys($array_sorted) as $index)
{
$array_final[] = $array_people[$index];
}
print_r($array_final);
Output:
Array
(
[0] => Array
(
[name] => Mihir
[salary] => 12000
)
[1] => Array
(
[name] => Raj
[salary] => 15000
)
[2] => Array
(
[name] => Vijay
[salary] => 14000
)
)
The first thing you need to do, is to process the main array in a way, that allows you to keep just the items you want - this items need to be stored in a different (empty) array (in this case $array_people).
While detecting the items you need, you've to get out all the values you want to sort by - this can be done at the same time. It's just about creating a new array which will contain just the values you will sort by (in this case $array_sorted).
Then comes the easier part. The next thing to do is sorting the array. There exist a bunch of functions, that can help you with this.
The functions i've used (asort and arsort) are keeping the original key of the item, so you can sort the array containing all the people by the keys of the sorted array (see the code up above).
And that's all, now you have an array with filtered and sorted people :) ... hope, this helps you.
Okay after reading so many solutions I personally believe that some of them are totally confusing for a newbie so here is the solution I actually implemented which is totally simple and easy to understand the flow of multi-dimensional array.
foreach($newArray as $x=>$x_value){
foreach ($x_value as $y=> $y_value){
if($y_value['salary']>10000){
echo "<tr>";
echo "<td>"; echo $y_value['name']; echo "</td>";
echo "<td>"; echo $x; echo "</td>";
echo "<td>"; echo $y_value['salary']; echo "</td>";
echo "</tr>";
}
}
}
The output will be like, (if u use table )
Im struggling with displaying the country_name, country_prefix followed by the city_name and city_prefix to display in PHP
Array (
[0] => stdClass Object
(
[country_name] => Russian Federation
[country_prefix] => 7
[country_iso] => RU
[cities] => Array
(
[0] => stdClass Object
(
[city_id] => 107
[city_name] => Moscow
[city_prefix] => 495
[city_nxx_prefix] =>
[setup] => 0
[monthly] => 60.9
[isavailable] => 1
[islnrrequired] => 0
)
...
This above returns the $results array and Im currently using something like this but have tried many iterations.
echo '<br />Results: <br />';
foreach($result as $countries => $country) {
foreach($country as $details => $value) {
echo $value . "<br/>";
}
}
Try this:
foreach($results as $country){
// country name in $country->country_name
foreach($country->cities as $city){
echo $city->city_name.'<br/>';
}
}
As you've been told in comments, you have an array of objects. You can iterate it with foreach, but then you should access its properties using the proper syntax (->)
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>
I have an array which looks like:
Array
(
[0] => Array
(
[total words] => 1476
)
[1] => Array
(
[keyword] => difference
[count] => 82
[percent] => 5.56
)
[2] => Array
(
[keyword] => 2010
[count] => 37
[percent] => 2.51
)
[3] => Array
(
[keyword] => very
[count] => 22
[percent] => 1.49
)
)
I want to show the array content in a table of three column and three rows. Each row contains keyword, count and percent as a column and Total. Words will be shown in table caption.
Please help me ! I'm trying to run a for loop but don't know how to show the array content, because it looks like a multi dimensional array. Please help me.
This should be what you're after.
print '<table>';
$headers = array_keys(reset($array));
print '<tr>';
foreach($headers as $header){
print '<th>'.$header.'</th>';
}
print '<tr>';
foreach($array as $row){
print '<tr>';
foreach($row as $col){
print '<td>'.$col.'</td>';
}
print '</tr>';
}
print '</table>';
Implode is your friend in this case:
$arrayLength = count($myArray);
echo '<table>';
for($i=0;$i<$arrayLength;$i++){
echo '<tr><td>'.
.implode('</td><td>',$myArray[$i])
.'</td></tr>';
}
echo '</table>';
http://us2.php.net/manual/en/function.implode.php
you can iterate through your array using a foreach($array => $value) loop.
this code should do the trick:
<table>
<tr>
<th>Keyword</th>
<th>Count</th>
<th>%</th>
</tr>
<?php foreach ( $data as $row ): ?>
<tr>
<td><?php echo $row['keyword']; ?></td>
<td><?php echo $row['count']; ?></td>
<td><?php echo $row['percent']; ?></td>
</tr>
<?php endforeach; ?>
</table>
Lets say array is stored in variable $a.
foreach($item in $a) {
echo $item['keyword'] . " " . $item['count'] . " " . $item['percent'] . "<br>\n";
}
array_values — Return all the values of an array
print_r(array_values($array));
Further to Godea Andrei's answer above, if you are using print_r just use
print_r($array)
Calling array_values within the print_r call will strip off all associative naming of the array elements. If just using numerical array indexes it will still show the index value. E.g.
$a = array("red", "green", "blue");
print_r($a) will display
Array ( [0] => red [1] => green [2] => blue )
whereas
$b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
print_r($b) will display
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
If using array_values the output of the second example would be
Array ( [0] => 35 [1] => 37 [2] => 43 )