Related
<?php
$arr =
[
'name' => 'hussin' ,
"age" => 25,
'job' =>
[
'php', 'ajax'
]
];
foreach ($arr as $key => $value)
{
if(!is_array($arr[$key]))
echo $key .' '. $value."<br>";
else
foreach ($arr['job'] as $key => $value)
echo $key .' '. $value."<br>";
}
?>
result
name Hussien
age 27
0 php
1 ajax
Is there a better solution than this to print the results?
I have an associative array with regular data, including a array type, which is the best solution for accessing all data
I may be misunderstanding, but I think you're looking for a recursive algorithm:
function printAll(array $arr){
foreach($arr as $k => $v){
if(is_array($v)){
return printAll($v);
}
print $k . ":" . $v . "\r\n";
}
}
printAll(['name' => 'hussin' ,"age" => 25,'job' => ['php', 'ajax']]); // name:hussin age:25 0:php 1:ajax
Now, this can of course be improved to deal with other iterables and the nested array keys, but hopefully you get the jist.
I have a multi-dimensional array as follows:
Array
(
[lists] => Array
(
[0] => Array
(
[id] => 23ybdwhdwbed
[name] => TEST
(
[1] => Array
(
[id] => e223edsewed
[name] => TEST 2
(
)
)
I want to access the ID & name variables using a foreach loop.
I'm using this:
$x = 0;
foreach($lists as $list){
$listId = $list[$x]['id'];
$listName = $list[$x]['name'];
echo"$x | $listId $listName <br />";
$x++;
}
For some strange reason, I can only get the value of the first $listId & $name, not the second $listId or $name.
What am I doing wrong here?
You're assuming that you still need to provide the key for each child element. This is not the case.
try
foreach($lists as $list){
$listId = $list['id'];
$listName = $list['name'];
$listId $listName <br />";
}
the foreach() will iterate over them in turn.
if you do need the index number, do this instead.
foreach($lists as $x => $list){
where $x is the index.
The array you posted is wrong because it's missing closing ), so correct that (I think that is TYPO mistake)
After that you need to do it like below:-
foreach($lists['lists'] as $key=> $list){
$listId = $list['id'];
$listName = $list['name'];
echo "$key | $listId $listName <br />";
}
Output:-https://eval.in/846464
Or an one-liner code:-
foreach($lists['lists'] as $key=> $list){
echo "$key | ".$list['id']." ".$list['name']." <br />";
}
Output:-https://eval.in/846465
Your foreach iterates the first, not the second level of your multi dimensional array.
Since the first level only holds the lists array as one and only element the loop only executes once.
Pass the lists key to the foreach instead like so:
$x = 0;
foreach($lists['lists'] as $list) {
echo "$x | " . $list['id'] . " " . $list['name'] . "<br />";
++$x;
}
Also note how in here I reference the list elements by name to make it easier to read.
I think those numerical indexed will just confuse you so try this instead:
$my_array = array(array("id" => "23ybdwhdwbed", "name" => "TEST"), array("id" => "e223edsewed", "name" => "TEST 2"));
To access the values: use:
foreach($my_array as $my_data){
echo "ID:" . $my_data["id"];
echo "<br>";
echo "NAME:" .$my_data["name"];
echo "<br><br>";
}
you just need to do:
foreach($lists['list'] as $listKey=>$listValue){
$listId = $listValue['id'];
$listName = $listValue['name'];
echo"$listKey | $listId : $listName <br />";
}
Try this, I fixed your array structure to work, this is also dynamic so it does not matter how many array you have 0 -> above
$array = array(
'lists' => array(
'0' => array(
'id' => '23ybdwhdwbed',
'name' => 'TEST 1'
),
'1' => array(
'id' => 'e223edsewed',
'name' => 'TEST 2'
)
)
);
foreach ($array as $key => $value) {
for($ctr = 0; $ctr < count($value); $ctr++){
echo 'ID: ' . $value[$ctr]['id'] . '<br>';
echo 'Name: : ' . $value[$ctr]['name'] . '<br><br>';
}
}
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 want to send more than on array in foreach() .
i know this way is false .whats the true method ?
$Fname = [1,2,3,4,5];
$Lname = [1,2,3,4,5];
$Addrs = [1,2,3,4,5];
$Mobile = [1,2,3,4,5];
$fields = array(
'name' => 'a',
'type' => 'b',
'value' => 'n',
'show' => 'd',
);
foreach($fields as $key => $n)
{
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$key} ,{$n} <br>";
}
If all your arrays have the same number of rows, you can use a for loop instead of a foreach, in conjunction with next() and current() for associative array:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
echo current($fields) . PHP_EOL;
next($fields);
}
The problem is that your arrays haven't same rows number...
So you have to add some condition like this:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
if( isset(current($fields)) )
{
echo current($fields) . PHP_EOL;
next($fields);
}
}
i know this way is false...? What's false about it?
foreach() will iterate over an array, not over multiple arrays.... if you absolutely need to iterate over multiple arrays within the same foreach() loop, you can use SPL's MultipleIterator, but it adds a lot more complexity to your code, and the approach that you've taken is as good as any
Just make sure that your keys match up in all the arrays; if they don't then you will have problems
foreach(array_values($fields) as $key => $n)
{
$k = array_keys($fields)[$key];
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$k} ,{$n} <br>";
}
Instead of storing your data like that, it'd be easier to store it in an array of associative arrays:
$people = array(
array(
'firstName' => 'Bruce',
'lastName' => 'Wayne',
'address' => '123 East St. Gotham City, XX USA'
'mobile' => '847-847-8475'
),
array(
'firstName' => 'Roland',
'lastName' => 'Deschain',
'address' => 'N/A'
'mobile' => '191-919-1919'
)
);
foreach($people as $person){
echo $person['firstName'] + ', ' + $person['lastName'];
echo $person['address'] + ', ' + $person['mobile'];
}
It's just a cleaner way to store/access your data, makes it easy to use one foreach as well.
Try this code
$arr1 = array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);
foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}
var_dump($arr1);
var_dump($arr2);
This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
Here is the code for pulling the data for my array
<?php
$link = mysqli_connect('localhost', 'root', '', 'mutli_page_form');
$query = "SELECT * FROM wills_children WHERE will=73";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
if($row = mysqli_fetch_assoc($result)) {
$data = unserialize($row['children']);
}
/* free result set */
mysqli_free_result($result);
}
?>
When I use print_r($data) it reads as:
Array ( [0] => Array ( [0] => Natural Chlid 1 [1] => Natural Chlid 2 [2] => Natural Chlid 3 ) )
I would like it to read as:
Natural Child 1
Natural Child 2
Natural Child 3
Instead of
print_r($data);
try
print "<pre>";
print_r($data);
print "</pre>";
print("<pre>".print_r($data,true)."</pre>");
I have a basic function:
function prettyPrint($a) {
echo "<pre>";
print_r($a);
echo "</pre>";
}
prettyPrint($data);
EDIT: Optimised function
function prettyPrint($a) {
echo '<pre>'.print_r($a,1).'</pre>';
}
EDIT: Moar Optimised function with custom tag support
function prettyPrint($a, $t='pre') {echo "<$t>".print_r($a,1)."</$t>";}
Try this:
foreach($data[0] as $child) {
echo $child . "\n";
}
in place of print_r($data)
I think that var_export(), the forgotten brother of var_dump() has the best output - it's more compact:
echo "<pre>";
var_export($menue);
echo "</pre>";
By the way: it's not allway necessary to use <pre>. var_dump() and var_export() are already formatted when you take a look in the source code of your webpage.
if someone needs to view arrays so cool ;) use this method.. this will print to your browser console
function console($obj)
{
$js = json_encode($obj);
print_r('<script>console.log('.$js.')</script>');
}
you can use like this..
console($myObject);
Output will be like this.. so cool eh !!
foreach($array as $v) echo $v, PHP_EOL;
UPDATE: A more sophisticated solution would be:
$test = [
'key1' => 'val1',
'key2' => 'val2',
'key3' => [
'subkey1' => 'subval1',
'subkey2' => 'subval2',
'subkey3' => [
'subsubkey1' => 'subsubval1',
'subsubkey2' => 'subsubval2',
],
],
];
function printArray($arr, $pad = 0, $padStr = "\t") {
$outerPad = $pad;
$innerPad = $pad + 1;
$out = '[' . PHP_EOL;
foreach ($arr as $k => $v) {
if (is_array($v)) {
$out .= str_repeat($padStr, $innerPad) . $k . ' => ' . printArray($v, $innerPad) . PHP_EOL;
} else {
$out .= str_repeat($padStr, $innerPad) . $k . ' => ' . $v;
$out .= PHP_EOL;
}
}
$out .= str_repeat($padStr, $outerPad) . ']';
return $out;
}
echo printArray($test);
This prints out:
[
key1 => val1
key2 => val2
key3 => [
subkey1 => subval1
subkey2 => subval2
subkey3 => [
subsubkey1 => subsubval1
subsubkey2 => subsubval2
]
]
]
print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.
foreach($data as $d){
foreach($d as $v){
echo $v."\n";
}
}
This may be a simpler solution:
echo implode('<br>', $data[0]);
This tries to improve print_r() output formatting in console applications:
function pretty_printr($array) {
$string = print_r($array, TRUE);
foreach (preg_split("/((\r?\n)|(\r\n?))/", $string) as $line) {
$trimmed_line = trim($line);
// Skip useless lines.
if (!$trimmed_line || $trimmed_line === '(' || $trimmed_line === ')' || $trimmed_line === 'Array') {
continue;
}
// Improve lines ending with empty values.
if (substr_compare($trimmed_line, '=>', -2) === 0) {
$line .= "''";
}
print $line . PHP_EOL;
}
}
Example:
[activity_score] => 0
[allow_organisation_contact] => 1
[cover_media] => Array
[image] => Array
[url] => ''
[video] => Array
[url] => ''
[oembed_html] => ''
[thumb] => Array
[url] => ''
[created_at] => 2019-06-25T09:50:22+02:00
[description] => example description
[state] => published
[fundraiser_type] => anniversary
[end_date] => 2019-09-25
[event] => Array
[goal] => Array
[cents] => 40000
[currency] => EUR
[id] => 37798
[your_reference] => ''
I assume one uses print_r for debugging. I would then suggest using libraries like Kint. This allows displaying big arrays in a readable format:
$data = [['Natural Child 1', 'Natural Child 2', 'Natural Child 3']];
Kint::dump($data, $_SERVER);
One-liner for a quick-and-easy JSON representation:
echo json_encode($data, JSON_PRETTY_PRINT);
If using composer for the project already, require symfony/yaml and:
echo Yaml::dump($data);
echo '<pre>';
foreach($data as $entry){
foreach($entry as $entry2){
echo $entry2.'<br />';
}
}
<?php
//Make an array readable as string
function array_read($array, $seperator = ', ', $ending = ' and '){
$opt = count($array);
return $opt > 1 ? implode($seperator,array_slice($array,0,$opt-1)).$ending.end($array) : $array[0];
}
?>
I use this to show a pretty printed array to my visitors
Very nice way to print formatted array in php, using the var_dump function.
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
I use this for getting keys and their values
$qw = mysqli_query($connection, $query);
while ( $ou = mysqli_fetch_array($qw) )
{
foreach ($ou as $key => $value)
{
echo $key." - ".$value."";
}
echo "<br/>";
}
I would just use online tools.
first do print_r(your_array)
Second copy the result and paste in http://phillihp.com/toolz/php-array-beautifier/
For single arrays you can use implode, it has a cleaner result to print.
<?php
$msg = array('msg1','msg2','msg3');
echo implode('<br />',$msg);
echo '<br />----------------------<br/>';
echo nl2br(implode("\n",$msg));
echo '<br />----------------------<br/>';
?>
For multidimensional arrays you need to combine with some sort of loop.
<?php
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
foreach($msgs as $msg) {
echo implode('<br />',$msg);
echo '<br />----------------------<br/>';
}
?>