I have a multidimensional array of fruits below.
$fruits = [
'ORANGE' =>
[
'Size' => '0.20',
'Cost' => '0.49',
'Lbs.' => '0.60',
]
'LEMON' =>
[
'Size' => '0.15',
'Cost' => '0.29',
'Lbs.' => '0.20',
]
];
I want to display the fruit array like below, but it is not working as expected.
-----| ORANGE | LEMON |
Size | 0.20 | 0.15 |
Cost | 0.49 | 0.29 |
Lbs. | 0.60 | 0.20 |
My code below is not quite doing what I expected. Any suggestions? Thank you!
echo '<table id="fruits" style="width:400px;border:1px solid black;">' . PHP_EOL;
echo '<tbody>' . PHP_EOL;
foreach ($fruits as $fruitkey => $fruitvalue) {
echo '<th>' . $fruitkey . '</th>';
foreach ($fruitvalue as $key => $value) {
echo '<tr>' . PHP_EOL;
echo '<td>' . PHP_EOL;
echo $key . PHP_EOL;
echo '</td>' . PHP_EOL;
echo '<td>' . PHP_EOL;;
echo number_format($value, 2) . PHP_EOL;
echo '</td>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
}
}
echo '</tbody>' . PHP_EOL;
echo '</table">' . PHP_EOL;
Can you try the below code
<?php
$fruits = [
'ORANGE' =>
[
'Size' => '0.20',
'Cost' => '0.49',
'Lbs.' => '0.60',
],
'LEMON' =>
[
'Size' => '0.15',
'Cost' => '0.29',
'Lbs.' => '0.20',
]
];
$keys = array_keys($fruits);
if(!empty($keys))
$innerKeys = array_keys($fruits[$keys[0]]);
echo '<table id="fruits" style="width:400px;border:1px solid black;">';
echo '<thead><tr>';
echo '<td>----</td>';
foreach($keys as $key)
echo '<td>'.$key.'</td>';
echo '</tr></thead>';
echo '<tbody>';
foreach($innerKeys as $inKey){
echo '<tr>';
echo '<td>'.$inKey.'</td>';
foreach($fruits as $fKey => $val){
echo '<td>'.$val[$inKey].'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
Demo Link
Related
I want to echo each persona included in the array $personas.
The following code echoes the first persona but it doesn't breaks the line and displays the second ("Mike").
Any help is much appreciated :)
<?php
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
foreach ( $person as $inner_param => $inner_value ) {
echo $param . ": " . $value . "<br>";
}
};
?>
Desired result:
Name: John | Age: 30 | Nationality: Spain |
Name: Mike | Age: 45 | Nationality: Peru |
Try this;
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
$text = "";
foreach ( $persona as $key => $val ) {
$text .= $key . ": " . $val . ' | ';
}
echo $text .'<br>';
}
I believe that I fixed it. Should it be as follows? Any better option?
foreach ($personas as $persona ) {
echo "<br>";
foreach ( $persona as $param => $value ) {
echo $param . ": " . $value . " | ";
}
};
I have following array of record which contains user as well as location information:
$arr =
[
[
'user_id' => 5,
'l_id' => 10,
'Name' => 'John Doe',
'Location' => 'Chicago',
'date' => '2021-10-02'
],
[
'user_id' => 5,
'l_id' => 11,
'Name' => 'John Doe',
'Location' => 'Houston',
'date' => '2021-10-02'
],
[
'user_id' => 6,
'l_id' => 12,
'Name' => 'Rob Doe',
'Location' => 'Dallas',
'date' => '2021-10-02'
],
[
'user_id' => 6,
'l_id' => 13,
'Name' => 'Rob Doe',
'Location' => 'Philadelphia',
'date' => '2021-10-02'
],
];
I'm trying to display same user/day location record in one td by using following code:
$html = '';
foreach ($arr as $ar) {
if ($ar['date'] == $ar['date']) {
$html .= '<tr>
<td>' . $ar['Name'] . '</td>
<td>' . $ar['date'] . '</td>
<td>' . $ar['Location'] . '</td>
</tr>';
}
}
HTML:
<table>
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<?= $html; ?>
</tbody>
</table>
But it's repeating same date record multiple times (Name, Date):
Name Date Location
John Doe 2021-10-02 Chicago
John Doe 2021-10-02 Houston
Rob Doe 2021-10-02 Dallas
Rob Doe 2021-10-02 Philadelphia
And I want result like this:
Name Date Location
John Doe 2021-10-02 Chicago
Houston
--------------------------------------------
Rob Doe 2021-10-02 Dallas
Philadelphia
Use this function for creating your required data:
function arrayChanger($oldArray) {
$newArray = array();
foreach ($oldArray as $v) {
if (!isset($newArray[$v['user_id']])) {
$newArray[$v['user_id']] = array(
'user_id' => $v['user_id'],
'dataArray' => array()
);
}
$newArray[$v['user_id']]['dataArray'][] = array(
'l_id' => $v['l_id'],
'Name' => $v['Name'],
'Location' => $v['Location'],
'date' => $v['date'],
);
}
return $newArray;
}
And then you can use that by your array:
$html = '<table>
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Location</th>
</tr>
</thead>
<tbody>';
foreach (arrayChanger($arr) as $newArrayKey => $newArrayValue) {
if (count($newArrayValue['dataArray']) <= 1) {
$html .= '<tr>
<td>' . $value['Name'] . '</td>
<td>' . $value['date'] . '</td>
<td>' . $value['Location'] . '</td>
</tr>';
} else {
$i = 0;
foreach ($newArrayValue['dataArray'] as $key => $value) {
$html .= '<tr>';
($i === 0) ? $html .= '<td>' . $value['Name'] . '</td>' : $html .= '<td> </td>';
($i === 0) ? $html .= '<td>' . $value['date'] . '</td>' : $html .= '<td> </td>';
$html .= '<td>' . $value['Location'] . '</td>';
$html .= '</tr>';
$i = $i + 1;
}
}
}
$html .= '</tbody>
</table>';
The output would be as your need:
Name
Date
Location
John Doe
2021-10-02
Chicago
Houston
Rob Doe
2021-10-02
Dallas
Philadelphia
Edit:
As changes in question, I changed my answer so we have the function:
function arrayChanger($oldArray)
{
$newArray = array();
foreach ($oldArray as $v) {
if (!isset($newArray[$v['user_id']])) {
$newArray[$v['user_id']] = array(
'user_id' => $v['user_id'],
'l_id' => $v['l_id'],
'Name' => $v['Name'],
'date' => $v['date'],
'UserLocations' => array()
);
}
$newArray[$v['user_id']]['UserLocations'][] = array(
'Location' => $v['Location'],
);
}
return $newArray;
}
And after that creating the HTML:
$html = '<table>
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Location</th>
</tr>
</thead>
<tbody>';
foreach (arrayChanger($arr) as $newArrayKey => $newArrayValue) {
$html .= '<tr>
<td>' . $newArrayValue['Name'] . '</td>
<td>' . $newArrayValue['date'] . '</td>
<td>';
foreach ($newArrayValue['UserLocations'] as $key => $value) {
$html .= $value['Location'] . "<br>";
}
$html .= '</td>
</tr>';
}
$html .= '</tbody>
</table>';
The output will:
Name
Date
Location
John Doe
2021-10-02
ChicagoHouston
Rob Doe
2021-10-02
DallasPhiladelphia
You can make an new Array where you merge the date and location.
$newArr = [];
foreach($arr as $item) {
if(isset($newArr[$item['Name']])) {
$newArr[$item['Name']]['Location'][] = $item['Location'];
$newArr[$item['Name']]['date'][] = $item['date'];
} else {
$newArr[$item['Name']]['user_id'] = $item['user_id'];
$newArr[$item['Name']]['l_id'] = $item['l_id'];
$newArr[$item['Name']]['Name'] = $item['Name'];
$newArr[$item['Name']]['Location'] = [$item['Location']];
$newArr[$item['Name']]['date'] = [$item['date']];
}
}
print_r($newArr);
output would be:
Array
(
[John Doe] => Array
(
[user_id] => 5
[l_id] => 10
[Name] => John Doe
[Location] => Array
(
[0] => Chicago
[1] => Houston
)
[date] => Array
(
[0] => 2021-10-02
[1] => 2021-10-02
)
)
[Rob Doe] => Array
(
[user_id] => 6
[l_id] => 12
[Name] => Rob Doe
[Location] => Array
(
[0] => Dallas
[1] => Philadelphia
)
[date] => Array
(
[0] => 2021-10-02
[1] => 2021-10-02
)
)
)
Then you can use your loop. And for the elements date and location you can use the php implode (implode(',', [])) function. That will be the easiest way.
Try this code which print name and date only the first time:
$html = '';
$count=0;
foreach ($arr as $ar) {
if ($ar['date'] == $ar['date']) {
if($count == 0){
$html .= '<tr>
<td>' . $ar['Name'] . '</td>
<td>' . $ar['date'] . '</td>
<td>' . $ar['Location'] . '</td>
</tr>';
$count++;
}
else{
$html .= '<tr>
<td></td>
<td></td>
<td>' . $ar['Location'] . '</td>
</tr>';
$count=0;
}
}
}
Im having some problem displaying a multidimensional array...
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
Basically I want to display everything and also save it in a variable...
echo "<ul>";
foreach($copyscape as $name => $value)
{
echo "<li>" . $name . " : ". $value . "</li>";
}
echo "</ul>";
I tried inserting another set of foreach inside but it gives me an
Invalid argument supplied for foreach()
Try with this code :
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
function test_print($item, $key)
{
echo "<li>" . $key . " : ". $item . "</li>";
}
echo "<ul>";
array_walk_recursive($copyscape, 'test_print');
echo "</ul>";
use this
foreach ($copyscape as $key=>$value){
echo "<li>" . $key. " : ". $value. "</li>"; // this for main Array
if (is_array ($value))
{
foreach ($value as $childArrayKey => $childArrayValue ){
echo "<li>" . $childArrayKey . " : ". $childArrayValue . "</li>"; // this for childe array
}
}
}
or
foreach ($copyscape as $key=>$value){
echo "<li>" . $key. " : ". $value. "</li>"; // this for main Array
foreach ($value['result']['number'] as $childArrayKey => $childArrayValue ){
echo "<li>" . $childArrayKey . " : ". $childArrayValue . "</li>"; // this for childe array
}
}
In case if you want to have lists inside of lists (nested levels)..
function outputLevel($arr)
{
echo '<ul>';
foreach($arr as $name => $value)
{
echo '<li>';
if (is_array($value))
outputLevel($value);
else
echo $name . ' : ' . $value;
echo '</li>'
}
echo '</ul>';
}
outputLevel($copyscape);
Try following code:
<?php
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
MultiDimRecuArray($copyscape);
function MultiDimRecuArray($copyscape) {
echo "<ul>";
foreach ($copyscape as $key=>$val) {
if(is_array($val)){
MultiDimRecuArray($val);
}else{
echo "<li>" . $key . " : ". $val . "</li>";
}
}
echo "</ul>";
}
Try something with a recursive function, like this:
function printArray($array)
{
echo "<ul>";
foreach($array as $name=>$value)
{
if(is_array($value))
{
printArray($value);
}
else
{
echo "<li>" . $name . " : ". $value . "</li>";
}
}
echo "</ul>";
}
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
printArray($copyscape);
Use this
<?php
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
PrintMultiDimArray($copyscape);
function PrintMultiDimArray($copyscape) {
echo "<ul>";
foreach ($copyscape as $key=>$val) {
if(is_array($val)){
echo "<li>";
PrintMultiDimArray($val);
echo "</li>";
}else{
echo "<li>" . $key . " : ". $val . "</li>";
}
}
echo "</ul>";
}
?>
try this..
echo '<ul>';
displayList($copyscape);
echo '</ul>';
function displayList($arr)
{
foreach($arr as $name => $value) {
if (is_array($value)) {
displayList($value);
}
else {
echo '<li>';
echo $name . ' : ' . $value;
echo '</li>';
}
}
}
Use this:
function print_stuff($arr){
foreach($arr as $key => $val){
if(is_array($val)){
echo "$key: <ul>";
print_stuff($val);
echo "</ul>";
} else {
echo "<li>$key : $val</li>\n";
}
}
}
echo "<ul>";
print_stuff($copyscape);
echo "</ul>";
The code prints a nested list including the key name of the nested lists:
query : www.example.html
querywords : 444
count : 230
result:
number:
index : 1
url : http://www.archives.gov/exhibits/charters/declaration_transcript.html
title : Declaration of Independence - Text Transcript
minwordsmatched : 406
viewurl : http://view.copyscape.com/compare/w4med9eso0/1
Hey I have an array where I would like to sum the values of the first-level children at various levels of the array.
<?php
$group = Array('Electronics' => Array(
'6 - Cameras & Supplies' => Array(
'Cameras' => Array(
'Camcorders' => Array (
'Action Camcorders' => Array (
'total_ty_yest_sales' => 70.83,
'total_wo_dotcom_ty_yest_sales' => 401.59,
'east_ty_yest_sales' => 65.20
),
'Standard Camcorders' => Array (
'total_ty_yest_sales' => 96.09,
'total_wo_dotcom_ty_yest_sales' => 96.09,
'east_ty_yest_sales' => 68.21
),
'Surveillance' => Array(
'total_ty_yest_sales' => 84.00,
'total_wo_dotcom_ty_yest_sales' => 84.00,
'east_ty_yest_sales' => 26.00
)
),
'subCameras' => Array (
'Big Zoom' => Array(
'total_ty_yest_sales' => 31.66,
'total_wo_dotcom_ty_yest_sales' => 13.68,
'east_ty_yest_sales' => 1.47
),
'Pegged Cameras' => Array(
'total_ty_yest_sales' => 13.50,
'total_wo_dotcom_ty_yest_sales' => 5.50,
'east_ty_yest_sales' => 5.00
),
'Point-N-Shoot' => Array(
'total_ty_yest_sales' => 46.61,
'total_wo_dotcom_ty_yest_sales' => 10.35,
'east_ty_yest_sales' => 4.06
),
'Rugged Cameras' => Array(
'total_ty_yest_sales' => 87.04,
'total_wo_dotcom_ty_yest_sales' => 87.04,
'east_ty_yest_sales' => 65.20
),
'SLR' => Array(
'total_ty_yest_sales' => 50.19,
'total_wo_dotcom_ty_yest_sales' => 9.40,
'east_ty_yest_sales' => 1.37
)
)
) )
));
$totalSum = 0;
echo "<table>\n
<thead></thead>\n
<tbody>\n";
foreach($group as $gmm => $acctg_dept_nbrs) {
echo "<tr class=\"header\">\n
<td>" . $gmm . "</td>\n";
foreach ($acctg_dept_nbrs as $acctg_dept_nbr => $dept_catg_grp_descs) {
echo "<tr class=\"header\">\n
<td style=\"padding-left: 1em;\">" . $acctg_dept_nbr . "</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
$total_acctg_dept_nbr = 0;
foreach($dept_catg_grp_descs as $dept_catg_grp_desc => $dept_category_descs) {
echo "<tr class=\"header\">\n
<td style=\"padding-left: 2em;\">" . $dept_catg_grp_desc . "</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
$total_dept_catg_grp_desc = 0;
foreach($dept_category_descs as $dept_category_desc => $dept_subcatg_descs) {
echo "<tr class=\"header\">\n
<td style=\"padding-left: 3em;\">" . $dept_category_desc . "</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
foreach($dept_subcatg_descs as $dept_subcatg_desc => $values) {
echo "<tr>\n
<td style=\"padding-left: 4em;\">" . $dept_subcatg_desc . "</td>\n";
$sum = $values['total_ty_yest_sales'];
echo "<td style=\"width:100px;\">".$sum."</td>\n";
$sum = $values['total_wo_dotcom_ty_yest_sales'];
echo "<td style=\"width:100px;\">".$sum."</td>\n";
$sum = $values['east_ty_yest_sales'];
echo "<td style=\"width:100px;\">".$sum."</td>\n";
}
}
}
}
}
?>
I want to replace the "SUM"s in the output with the sum of the values of next level of indention.
This is not the most efficient thing to do, but you can create a function that calculates the sum of an array recursively:
function array_sum_recursive($array)
{
$sum = 0;
array_walk_recursive($array, function($item) use (&$sum) {
$sum += $item;
});
return $sum;
}
I have a php has below how i can echo in php.
i want to echo like this
Veg.Pizaa =>
Extra = > Cheese, price 50
Vegetables = > Avocado, price 25
The Array Is Below
array
(
'Veg.Pizaa' =>
(
array
(
'Extra' =>
(
array
(
'name' => string '25g Cheese' (length=10),
'price' => string '50' (length=2),
'quanty' => int 13,
'Vegetables' =>
),
array
(
'name' => string 'Avocado' (length=7),
'price' => string '25' (length=2),
'quanty' => int 13,
'Nuts' =>
),
array
(
'name' => string 'Almonds' (length=7),
'price' => string '30' (length=2),
'quanty' => int 21
)
)
)
)
)
I've tried the following code
foreach($sub as $sub) {
var_dump($sub);
echo "<tr>";
echo "<td><h3 style='font-weight: bolder; color: Maroon; line-height: 10px;'>".$sub[0]['productname']
."</h3></td>";
echo "<td><h3 style='font-weight: bolder; color: Maroon; line-height: 10px;'>".$sub[0]['qty']
."</h3></td>";
echo "</tr>";
}
$array = ...;
foreach( $array as $key => $val )
{
echo $key . " =>\n";
foreach( $val as $key2 => $val2 )
{
echo "\t" . $key2 . ' => ' . $val2['name'] . "\n";
}
}
foreach($array as $key => $val)
{
echo $key.' ';
if(is_array($val)
{
foreach($val as $name => $qty)
{
if($name=='name')
{
echo $qty;
}
if($name=='price')
{
echo $name.', '.$qty.'\n<br>';
}
}
}
}
Why don't you just do:
print_r($array)
That's what I'd use to debug an array.