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.
Related
I have a very simple multidimensional array and some PHP code. The code should print the p_id values, but it does not do it. Do I really have to add one foreach more or is there other ways?
And here is the array:
Array (
[2764] => Array (
[status] => 0
[0] => Array (
[p_id] => 2895
)
[1] => Array (
[p_id] => 1468
)
)
[5974] => Array (
[status] => 0
[0] => Array (
[p_id] => 145
)
[1] => Array (
[p_id] => 756
)
)
)
Here is my PHP code:
foreach($arr as $innerArray)
foreach($innerArray as $key => $value)
echo $key . "=>" . $value . "<br>";
It prints:
status=>0
0=>Array
1=>Array
status=>0
0=>Array
1=>Array
foreach($arr as $a => $a_value)
{
echo $a . '<br>';
foreach($a_value as $av_arr => $av)
{
if(!is_array($av))
{
echo $av_arr . '=>' . $av . '<br>';
}
else
{
foreach($av as $inner_av => $inner_av_val)
{
echo $inner_av . '=>' . $inner_av_val . '<br>';
}
}
}
}
This simple call to array_walk_recursive() produces the output requested in the question:
array_walk_recursive(
$arr,
function ($value, $key) {
echo $key . "=>" . $value . "<br>";
}
);
But it doesn't make much sense as the output mixes the values of status with the values of p_id.
I would go for a more structured display using the original code with a little more meaning for the names of the variables:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo as $key => $value) {
if ($key == 'status') {
// Ignore the status; it was already displayed
continue;
}
foreach ($value as $prodInfo) {
printf(" Product ID: %d\n", $prodInfo['p_id']);
}
}
}
The structure of the input array tells me you should first fix the code that generates it. It should group all the products (the values that are now indexed by numeric keys) into a single array. It should look like this:
$input = array(
'2764' => array(
'status' => 0,
'products' => array(
2895 => array(
'p_id' => 2895,
'name' => 'product #1',
// more product details here, if needd
),
1468 => array(
'p_id' => 1468,
'name' => 'product #2',
),
// more products here
),
// more categories here
),
Then the code that prints it will look like this:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo['products'] as $prodInfo) {
printf(" %s (ID: %d)\n", $prodInfo['name'], $prodInfo['p_id']);
// etc.
}
}
Use a recursive function:
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]."\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
Working example:
$arr = [
2764 => [
'status' => 0,
['p_id' => 100],
],
4544 => [
'status' => 0,
['p_id' => 100],
],
['p_id' => 100],
];
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]"\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
printIds($arr);
The function loops all entries of a given array and echo's them out, if they contain an array with a key named "p_id". If it does find a nested array, then it does loop also all child arrays.
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.
$new_arr = [
[
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
],
[
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
],
[
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
],
[
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
]
];
I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.
Array (
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36139 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36127, 36129
[code_name] => 36127, 36129 - Bagan Pete
)
)
I try this method, but not fix at 'code_name'
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code'] . ' - ' . $value['name']
);
}
}
$out = array_values($out);
print_r($out);
You have to check duplicate name by in_array and update exist array value .If not exist insert that value to $out array .
$out = array();
foreach($new_arr as $k=>$v) {
//empty array state
if(count($out) == 0) {
$out[] = $v;
continue;
}
foreach ($out as $key => $value) {
if(in_array($v["name"],$value)) {
$out[$key]["code"] .= ",".$v["code"];
//for the code_name output as OP described
$nn = explode("-", $value["code_name"]);
$l = count($nn) - 1;
unset($nn[$l]);
$out[$key]["code_name"] = implode($nn).",".$v["code_name"];
break;
} else {
if((count($out)-1) == $key) {
$out[] = $v;
}
}
}
}
var_dump($out);
For someone have problem like me, this method for fix it:
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
$out[$value['name']]['code_name'] .= ', '.$value['code'] . ' - ' . $value['name'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code']
);
}
}
$out = array_values($out);
print_r($out);
Final result;
Array
(
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36137 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36129, 36127
[code_name] => 36129, 36127 - Bagan Pete
)
)
Please try below one as another approach:
<?php
$arr = Array (
Array
(
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
),
Array
(
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
)
);
$newarr = array();
$finalArr = array();
foreach($arr as $aa) {
$newarr[$aa['name']][] = $aa;
}
foreach($newarr as $kk => $bb) {
foreach($bb as $cc) {
$finalArr[$kk]['name'] = $cc['name'];
if(isset($finalArr[$kk]['code'])) {
$finalArr[$kk]['code'] = $finalArr[$kk]['code'].','.$cc['code'];
} else {
$finalArr[$kk]['code'] = $cc['code'];
}
if(isset($finalArr[$kk]['code_name'])) {
$finalArr[$kk]['code_name'] = $finalArr[$kk]['code_name'].','.$cc['code_name'];
} else {
$finalArr[$kk]['code_name'] = $cc['code_name'];
}
}
}
echo "<pre>";
print_r($finalArr);
echo "</pre>";
?>
Definitely avoid any suggestions that use more than one loop to group and concatenate the data.
I do endorse #Opsional's snippet. An alternative approach is to push reference variables into the result array, then only concatenate comma-separated values to the appropriate reference variable.
Code: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($ref[$row['name']])) {
$ref[$row['name']] = $row;
$result[] = &$ref[$row['name']];
} else {
$ref[$row['name']]['code'] .= ', ' . $row['code'];
$ref[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export($result);
For any purist developers that insist on destroying references, call unset($ref) after the loop.
Here is a streamlined version of #Opsional's snippet: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($result[$row['name']])) {
$result[$row['name']] = $row;
} else {
$result[$row['name']]['code'] .= ', ' . $row['code'];
$result[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export(array_values($result));
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
So, I want to print the following three dimensional array in an HTML table.
array ( 'BTC_YACC' => array ( 0 => array ( 'orderNumber' => '3585379', 'type' => 'sell', 'rate' => '0.0001', 'amount' => '128', 'total' => '0.0128', 'date' => '2014-05-18 08:54:37', ), ), )
This is what I came up with: (OrderNumber = OrderID).
$tableopenorders = "<table><th>OrderID</th><th>Type</th><th>Rate</th><th>Amount</th><th>Total in BTC</th><th>Date placed</th><tr>";
for($element = 0; $element < count($decodedopenorders); $element++) {
$tableopenorders .= "<tr>";
for($row = 0; $row < 1; $row++) {
for ($col = 0; $col < 6; $col++) {
$tableopenorders .= "<td>".$decodedopenorders[$element][$row][$col]."</td>";
}
}
$tableopenorders .= "</tr>";
}
$tableopenorders .= "</table>";
There's a maximum of "count($decodedopenorders)" $elements, max. 1 $row and 6 rows in the $decodedopenorders array. The iterator starts a 0, so I used <.
Why does this not work?
When you loop through your arrays you have changed the key to be something other than the typical 0, 1, 2, 3. When you change the key the $decodedopenorders[0] no longer works and instead you would have to call $decodedopenorders['BTC_YACC']; So here is the code I got to work:
$decodedopenorders = array (
'BTC_YACC' => array (
0 => array (
'orderNumber' => '3585379',
'type' => 'sell',
'rate' => '0.0001',
'amount' => '128',
'total' => '0.0128',
'date' => '2014-05-18 08:54:37')
)
);
$tableopenorders = "<table><th>OrderID</th><th>Type</th><th>Rate</th><th>Amount</th><th>Total in BTC</th><th>Date placed</th><tr>";
foreach ($decodedopenorders as $element => $value) {
$tableopenorders .= "<tr>";
foreach ($decodedopenorders[$element] as $row => $value){
foreach ($decodedopenorders[$element][$row] as $order) {
$tableopenorders .= "<td>". $order ."</td>";
}
}
$tableopenorders .= "</tr>";
}
$tableopenorders .= "</table>";
echo $tableopenorders;
I have a multidimensional array in the following format:
$array = array (
0 =>
array (
'date' => '2013-03-25',
'name' => 'Bob',
'time' => '11'
),
1 =>
array (
'date' => '2013-03-25',
'name' => 'Brian',
'time' => '13'
),
2 =>
array (
'date' => '2013-03-26',
'name' => 'Jack',
'time' => '14'
),
3 =>
array (
'date' => '2013-03-26',
'name' => 'Bob',
'time' => '14'
)
);
I am trying to get the names and corresponding times for each date. I have got the names using the following method:
$array2 = array();
foreach($array as $item) {
$array2[$item['date']][] = $item['name'];
}
and then using:
foreach($array2[$date] as $name)
to run a query on the names returned. But I am not sure how to get the corresponding 'time' key for each 'name' key in the second foreach loop.
Why you don't want to store both name and time for each date key?
$array2 = array();
foreach ($array as $item) {
$array2[$item['date']] []= array($item['time'], $item['name']);
}
You can reach name and time with this code:
foreach ($array2 as $row) {
$name = $row[0];
$time = $row[1];
}
You can try
$list = array();
foreach ( $array as $k => $item ) {
$list[$item['date']][] = array(
$item['name'],
$item['time']
);
}
foreach ( $list as $date => $data ) {
echo $date, PHP_EOL;
foreach ( $data as $var ) {
list($name, $time) = $var;
echo $name, " ", $time, PHP_EOL;
}
echo PHP_EOL;
}
Output
2013-03-25
Bob 11
Brian 13
2013-03-26
Jack 14
Bob 14
try the following:
foreach($array as $item) {
$array2[$item['date'][] = array('name' => $item['name'], 'time' => $item['time']);
}
foreach($array2[$date] as $name) {
echo $name['name'] . ' => ' . $name['time'] . "\n";
}