I have a complex array, something like that:
Array {
k1 => text1
k2 => Array {
k3 =>text2
k4 => Array {
k5 => text3
}
k6 => text4
}
}
And i want to echo the array but to indent every subarray like this:
key: k1 >> value: text1
Array key: k2 >> values:
key: k3 >> value: text2
Array key: k4 >> values:
key: k5 >> value: text3
key: k6 >> value: text4
Let me know if you need any details.
Here's a recursive function that will indent:
(Edited: Indentation wasn't working properly for all subelements, now it does)
function arrayPrettyPrint($arr, $level = 0) {
foreach($arr as $k => $v) {
for($i = 0; $i < $level; $i++)
echo " "; // You can change how you indent here
if(!is_array($v))
echo($k . " => " . $v . "<br/>");
else {
echo($k . " => <br/>");
arrayPrettyPrint($v, $level+1);
}
}
}
$arr = array(
1, 2, 3,
array( 4, 5,
array( 6, 7, array( 8 )))
);
arrayPrettyPrint($arr);
It's print array like your.
<?php
function print_array($array, $tabs = '') {
$result = '';
if (is_array($array)) {
foreach ($array as $k => $v) {
if (is_array($v)) {
$result .= $tabs . 'Array key: '. $k . ' >> values: ' . PHP_EOL . print_array($v, $tabs."\t");
} else {
$result .= $tabs . 'key: ' . $k . ' value: ' . $v . PHP_EOL;
}
}
} else {
$result = $array . PHP_EOL;
}
return $result;
}
$array = array(
'k1' => 'text1',
'k2' => array(
'k3' => 'text2',
'k4' => array(
'k5' => 'text3'
),
'k6' => 'text4'
)
);
echo print_array($array);
?>
Try building on this quick function:
function recurseDisplay($my_array,$padding = 2){
echo "<br />";
foreach($my_array as $item){
if (is_array($item)){
$padding += 10;
for ($p = 0; $p < $padding; $p++){
echo " ";
}
echo "Array: {" ;
recurseDisplay($item,$padding);
echo " <br /> } <br />";
}
else{
for ($p = 0; $p < $padding; $p++){
echo " ";
}
echo "key :" . $item . "<br />";
}
}
}
recurseDisplay($my_array);
Would var_dump do the job for you?
myVar = Array {
k1 => text1
k2 => Array {
k3 =>text2
k4 => Array {
k5 => text3
}
k6 => text4
}
}
try it
var_dump(myVar)
It appears that this question was asked before here. This was the solution by KeithGrant
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo "\t" . $vals['comment_content'];
RecursiveWrite($vals['child']);
}
}
Related
I'm learning array and loop in php. But can't print the array with keys & values. How can I do this?
<?php
$marks = array (
"Alice" => array (
"physics" => "60",
"math" => "65"
),
"Bob" => array (
"physics" => "40",
"math" => "45"
)
);
foreach ( $marks as $key => $value) {
foreach ( $key as $key2 => $value2 ) {
echo $key . " : " . $key2 . " - " . $value2 . "<br>";
};
};
?>
In the nested foreach you have to iterate over the $value which holds the array.
foreach ( $marks as $key => $value) {
foreach ( $value as $key2 => $value2 ) {
// -------^^^^^^-------
echo $key . " : " . $key2 . " - " . $value2 . "<br>";
}
};
Use this
foreach ( $marks as $key => $value) {
foreach ( $value as $key2 => $value2 ) {
echo $key . " : " . $key2 . " - " . $value2 . "<br>";
}
}
This way it could be more readable to fix it and clear up confusion:
$marks = array(
'Alice' => array(
'physics' => 60,
'math' => 65,
),
'Bob' => array(
'physics' => 40,
'math' => 45,
),
);
// Loop students
foreach($marks as $name => $grades){
// Loop their grades
foreach ($grades as $subject => $score){
echo $name . ' : ' . $subject . ' - ' . $score . '<br>';
}
}
Please note that the numbers are without quotes. This will allow you to use them as numbers to do further calculations.
I want to foreach the game name and info and each game must filter as platform_name.
$list = (object)[];
$list->egame =
[
(object)['platform_name'=>'TT', 'game'=>(object)[(object)['game_name'=>'game1', 'info'=>'test1'],(object)['game_name'=>'game2', 'info'=>'test2'],(object)['game_name'=>'game3', 'info'=>'test3']]],
(object)['platform_name'=>'TG', 'game'=>(object)[(object)['game_name'=>'game4', 'info'=>'test4'],(object)['game_name'=>'game5', 'info'=>'test5']]],
(object)['platform_name'=>'TBIN', 'game'=>(object)[(object)['game_name'=>'game6', 'info'=>'test6']]]
];
?>
Try this
$list = (object)[];
$list->egame =
[
(object)['platform_name' => 'TT', 'game' => (object)[(object)['game_name' => 'game1', 'info' => 'test1'], (object)['game_name' => 'game2', 'info' => 'test2'], (object)['game_name' => 'game3', 'info' => 'test3']]],
(object)['platform_name' => 'TG', 'game' => (object)[(object)['game_name' => 'game4', 'info' => 'test4'], (object)['game_name' => 'game5', 'info' => 'test5']]],
(object)['platform_name' => 'TBIN', 'game' => (object)[(object)['game_name' => 'game6', 'info' => 'test6']]]
];
$arr = (array)$list->egame;
for ($i = 0; $i < count($arr); $i++) {
foreach ($arr[$i] as $key => $value) {
$aa = (array)$arr[$i]->game;
foreach ($aa as $k => $v) {
echo $aa[$k]->game_name." ".$aa[$k]->info."<br/>";
}
echo "<br/>";
}
}
Here You go:
<?php
$list = (object)[];
$list->egame =
[
(object)['platform_name'=>'TT', 'game'=>(object)[(object)['game_name'=>'game1', 'info'=>'test1'],(object)['game_name'=>'game2', 'info'=>'test2'],(object)['game_name'=>'game3', 'info'=>'test3']]],
(object)['platform_name'=>'TG', 'game'=>(object)[(object)['game_name'=>'game4', 'info'=>'test4'],(object)['game_name'=>'game5', 'info'=>'test5']]],
(object)['platform_name'=>'TBIN', 'game'=>(object)[(object)['game_name'=>'game6', 'info'=>'test6']]]
];
foreach ( $list->egame as $eg ) {
foreach ( $eg->game as $game ) {
echo "game: " . $game->game_name . " info: " . $game->info . "<br>";
}
}
?>
Edit #1
Includes platform:
foreach ( $list->egame as $eg ) {
foreach ( $eg->game as $game ) {
echo "platform: " . $eg->platform_name . " game: " . $game->game_name . " info: " . $game->info . "<br>";
}
}
I would like the data to be echoed out in this format
[0] - [name][description]
[1] - [name][description]
[2] - [name][description]
$options = array('guide_info' => $guide_info);
$guide_info = array( 'guide_name' => $guide_name,
'guide_description' => $guide_description
);
I created two foreach loops to try and echo out the name and description of each, like this:
foreach ($options as $key => $value) {
foreach ($guide_info as $type => $info){
$html .= $type . " " . $info . "\n";
}
}
but I receive errors about invalid argument supplied for foreach() on the second loop.
Currently my print_r($options) shows
Array ( [guide_name] => f
[guide_description] => fff
[0] => Array (
[guide_name] => fsss
[guide_description] => sssss
)
)
and my echo prints
guide_name fsss
guide_description sssss
guide_name fsss
guide_description sssss
guide_name fsss
guide_description sssss
How would I be able to echo out the correct information that print_r is showing?
Use a recursive function to echo out the name and description values in the desired format.
function process_array($arr, $counter){
foreach($arr as $key => $value){
if(is_array($value)){
process_array($value, ++$counter);
}else{
if($key == "guide_name"){
echo "[" . $counter . "] - [" . $value . "][";
}else{
echo $value . "]<br />";
}
}
}
}
// Here $options is your original array
process_array($options, 0);
Output:
[0] - [f][fff]
[1] - [fsss][sssss]
$guide_info = array( 'guide_name' => 'guid name',
'guide_description' => 'guid description',
);
$options = array('guide_info' => $guide_info);
foreach ($options as $key => $value) {
foreach($value as $a => $b) {
echo $a," =",$b ;
}
}
or for print_r
foreach ($options as $key => $value) {
print_r($value) ;
}
Why are you putting the $guide_info in $options.If you want all the entries from $guide_info, you can do this-
for($i = 0; $i < count($guide_info); $i++){
$html .= $type . " " . $info . "\n";
}
-> considering $guide_info is a multidimensional array like = array( [0] => 'guide_name' => $guide_name,
'guide_description' => $guide_description)
If for some reason $guide_info IS important, I would suggest it to be an indexed array not assoc.. Hope you find the solution :)
Here is the example code:
<?php
$arr = array(
array(
'company' => array(
'code' => 'ccd1',
'name' => 'cnm1'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
)
)
) ,
array(
'company' => array(
'code' => 'ccd2',
'name' => 'cnm2'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
) ,
array(
'code' => 'pcd3',
'name' => 'pnm3'
)
)
)
);
echo "<pre>"; print_r($arr); echo "</pre>";
$AI = 1;
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
foreach($value['products'] as $value2){
echo " ".$value2['name']."<br />";
}
}
I don't know how to explain it, but what I want is to add auto increment in sub foreach loop, like this:
1.cnm1 (2)
1.pnm1
2.pnm2
2.cnm2 (3)
1.pnm1
2.pnm2
3.pnm3
Usually you can just use the foreach keys plus one. As another alternative, if this is just for presentation, just use ordered lists:
echo '<ol>';
foreach($arr as $ar1) {
echo '<li>' . $ar1['company']['name'] . ' (' . count($ar1['products']) . ')</li>';
echo '<ol>';
foreach($ar1['products'] as $ar2) {
echo "<li>{$ar2['name']}</li>";
}
echo '</ol>';
}
It'll number those items accordingly. No need for addition. Plus you can use CSS to style the list,
You can access the key/index of an foreach :
foreach($arr as $i => $value){
$total_products = count($value['products']);
echo ($i+1).'.'.$value['company']['name'].' ('.$total_products .')<br />';
foreach($value['products'] as $j => $value2){
echo ' '.($j+1).'.'.$value2['name'].'<br />';
}
}
Here you go.
$arr = array(array('company'=>array('code'=>'ccd1', 'name'=>'cnm1'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'))), array('company'=>array('code'=>'ccd2', 'name'=>'cnm2'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'), array('code'=>'pcd3', 'name'=>'pnm3'))));
echo "<pre>";
print_r($arr);
echo "</pre>";
$AI = 1;
foreach($arr as $value)
{
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$k = 0;
foreach($value['products'] as $value2)
{
echo " ".$k++.". ".$value2['name']."<br />";
}
}
This also worked for me:
foreach($value['products'] as $key2=>$value2){
$AI2 = $key2+1;
echo " ".$AI2.".{$value2['name']}<br />";
}
You can try this:
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$sub=1;
foreach($value['products'] as $value2){
echo " ".$sub++.'.'.$value2['name']."<br />";
}
}
I would like to display some array data in relation to a competition, each player is ranked by the number of points they have, however if a player has the same amount of points to somebody else they should both have the exact same ranking position.
For instance...
1st Bob 500pts
2nd Joe 350pts
3rd Tom 250pts
3rd Tim 250pts
5th Jay 100pts
In this instance, as Tom & Tim have the exact same number of points they should be joint third, making the next person down 5th (rather than 4th), can anyone suggest the best way to achieve this with a simple array similar to follows
array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
Can anyone suggest the 'cleanest' solution for achieving this
This code will work for you:
$array = array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
arsort($array, SORT_NUMERIC);
$previousPoints = null;
$position = $total = 1;
foreach($array as $name=>$points) {
if ($points != $previousPoints) {
$position = $total;
}
echo $position.' '.$name.' '.$points."\n";
$previousPoints = $points;
$total++;
}
Online demo here.
$ar = array(
'Bob' => 500,
'Tim' => '250',
'Joe' => '350',
'Tom' => '250',
'Jay' => '100'
);
arsort($ar, SORT_NUMERIC);
$i = 1;
$previous = 1;
$previousPosition = 1;
foreach($ar as $k => $v)
{
if($v === $previous)
{
//If the value now is the same as the previous value use the previous position
echo "Position: $previousPosition, $k : $v <br />";
}
else
{
echo "Position: $i, $k : $v <br />";
}
//Previous value
$previous = $v;
//Previous Position
$previousPosition = $i;
//Always increment the value
$i++;
}
Try below code:
$a = array('Bob' => 500, 'Joe' => '350', 'Tom' => '250', 'Tim' => '250', 'Jay' => '100');
arsort($a);
$rank = 1;
$index = 1;
$prevUserPoints = 0;
foreach($a as $name=>$points) {
if($points != $prevUserPoints) {
$rank = $index;
}
$index++;
echo $rank . ' ' . $name . ' ' . $points . "\n";
$prevUserPoints = $points;
}
For displaying 1 as 1st, 2 as 2nd etc, you can use something like below:
function ordSuffix($n) {
$str = "$n";
$t = $n > 9 ? substr($str,-2,1) : 0;
$u = substr($str,-1);
if ($t==1) return $str . 'th';
else switch ($u) {
case 1: return $str . 'st';
case 2: return $str . 'nd';
case 3: return $str . 'rd';
default: return $str . 'th';
}
}
example: echo ordSuffix(23); This prints 23rd
Just a basic and alternative point of view you might want to consider.
$arr = [
"Joe" => "350",
"Tom" => "250",
"Jay" => "200",
"Tim" => "250",
"Bob" => "500",
"John" => "250" ,
"Paul" => "251.40"
];
$rank = array();
array_walk($arr,function($v, $k) use (&$rank)
{
if(isset($rank[$v]))
{
$rank[$v][$k] = $v;
asort($rank[$v]); //alphabetical order John, Tim, Tom
} else
{
$rank[$v] = array($k => $v);
}
});
krsort($rank);
var_dump(array_values($rank));