echoing out two dimensional associative arrays in php - php

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 :)

Related

How do I get values inside this multi-dimensional array

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>';
}
}

How to put out array

How can I put out the following array?
$newdata = array (
'Spiel_ID' => $ausgabeT->Spielplan_ID,
'Heimmannschaft' => $ausgabeVereinT->Name,
'Gastmannschaft' => $ausgabeVereinTGast->Name
);
var_dump($newdata);
foreach($newdata as $result) {
echo $result['Spiel_ID'], '<br>';
}
For the echo I get error:
Illegal string offset 'Spiel_ID'
You are trying to echo a value that doesn't exist.
When you use foreach ($newdata as $result) the $result is a string, not an array.
You have two options, based on this structure:
$newdata = array (
'Spiel_ID' => $ausgabeT->Spielplan_ID,
'Heimmannschaft' => $ausgabeVereinT->Name,
'Gastmannschaft' => $ausgabeVereinTGast->Name
);
Option 1 — Display all values
foreach($newdata as $result) {
echo $result;
}
Option 2 — Display a single value
echo $newdata['Spiel_ID'];
Option 3 — Display Key + Value
foreach($newdata as $key => $value) {
echo $key . ' = ' . $value . '<br>';
}
All you need to do is just echo $result

PHP sort array by key 'value'

I have the following code which displays the results that I want. I'm trying to get it to sort on the key 'value' from the output below. So Eric, Eric 2, Eric 3
An example output of $resultnames is:
Array
(
[0] => Array
(
[Eric 2] => Asdf
)
[1] => Array
(
[Eric] => Asdf
)
[2] => Array
(
[Eric 3] => Asdf
)
)
So the key is the first name and the value of that key is the last name. I'm trying to sort the array by first name
foreach (array_chunk($uvugroups, 6, true) as $uvugroup)
{
foreach ($uvugroup as $uvustate) {
echo "<h4>Registrants</h4>";
$fnames = explode( '|', $uvustate['fname'] );
$lnames = explode( '|', $uvustate['lname'] );
$resultnames = array();
foreach ($fnames as $i => $key) {
$resultnames[] = array($key => $lnames[$i]);
}
foreach ($resultnames as $resultname) {
foreach ($resultname as $fkey => $lkey) {
echo "<ul>";
echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
echo "</ul>";
}
}
}
}
I tried to use ksort in different places in the code, but it didn't seem to have an effect.
It's a bit hard because the expected output is not defined in the question, but with this code as the contents of the second foreach it should produce a list sorted by first name.
$fnames = explode( '|', $uvustate['fname'] );
$lnames = explode( '|', $uvustate['lname'] );
$resultnames = array_combine($fnames, $lnames);
ksort($resultnames);
echo "<ul>";
foreach ($resultnames as $fkey => $lkey) {
echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
}
echo "</ul>";

PHP compare values in a single array and output the difference

I have an array that looks like this:
$rowarray(
[0] => [PID] => 97162 [TID] => 340 [StatsID] => 49678
[1] => [PID] => 97165 [TID] => 340 [StatsID] => 49673
[2] => [PID] => 97167 [TID] => 340 [StatsID] => 49675
[3] => [PID] => 97162 [TID] => 340 [StatsID] => 49679
)
Then my code looks like this:
$cntr=0;
foreach($rowarray as $row)
{
echo "<tr><td>$row[PID] $row[TID] $row[StatsID] </td></tr>";
$cntr++;
}
Two things I want to do I want to be able not print the duplicates in the array but print the additional column that has a different value. So my desired output would look like this.
97162 340 49678 49679
97165 340 49673
97167 340 49675
I started out with the array_unique() but that only returned:
97162 340 49678
Assuming only the StatsID changes (not clear from the question)
$map = array();
foreach($rowarray as $row){
$k = $row["PID"] . '-' . $row["TID"];
if( !isset( $map[$k] ) ){
$map[$k] = array();
}
array_push( $map[$k], $row["StatsId"] );
}
foreach($map as $k=>$v){
$row = explode( '-', $k );
echo "<tr><td>$row[0] $row[1] " . implode( " ", $v ) . " </td></tr>";
}
Here's what I'd do:
Start by sorting the array (using usort to sort by PID, then by TID)
Initialize "last" variables ($last_PID and $last_TID). They will store the respective values in the loop
In the loop, first compare the "current" variables to the "last" ones, if they're the same then just echo the StatsID value.
If they're not the same, output the <tr> (but not the final </tr>, so the first part of the loop can add more StatsID values if necessary)
Still inside the loop, after outputting everything, update the "last" variables.
After the loop, output the final </tr>
This may not be optimal, but I'm pretty sure it'll work.
Transfer the $rowarray structure into a map of maps of arrays, like this:
$rowarray = array(
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49678),
array('PID' => 97165, 'TID' => 340, 'StatsID' => 49673),
array('PID' => 97167, 'TID' => 340, 'StatsID' => 49675),
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49679)
);
$keys = array();
foreach ($rowarray as $row) {
if (!is_array(#$keys[$row['TID']])) {
$keys[$rowarray['TID']] = array();
}
if (!is_array(#$keys[$row['TID']][$row['PID']])) {
$keys[$row['TID']][$row['PID']] = array();
}
$keys[$row['TID']][$row['PID']][] = $row['StatsID'];
}
foreach ($keys as $pid => $pid_arr) {
foreach ($pid_arr as $tid => $tid_arr) {
echo "<tr><td>$tid $pid " . implode(' ', $tid_arr) . "</td></tr>";
}
}
See this code in action
As far as I can tell, the only way to do this would be to loop through the array creating a new unique array as you go.
$unique = array();
foreach ($row as $value)
{
$key = $value['PID'];
if (isset($unique[$key]))
{
$unique[$key]['StatsID'] .= ' ' . $value['StatsID'];
}
else
{
$unique[$key] = $value;
}
}
Now, $unique would give you the results you're looking for and you can loop through the unique array and output your results (I also added your counter if needed):
$count = count($unique);
foreach ($unique as $row)
{
echo "<tr><td>{$row['PID']} {$row['TID']} {$row['StatsID']} </td></tr>";
}

Display an array in a readable/hierarchical format [duplicate]

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/>';
}
?>

Categories