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>";
Related
Say I have this PHP array()
$tour_from array
Array
(
[0] => Array
(
[0] => Dhaka
[1] => noakhali
)
[1] => Array
(
[0] => Chittagong
[1] => Sylhet
)
)
I want to make like this:
Dhaka - Noakhali
Chittagong - Sylhet
How can I do this?
I used this but it's the wrong way:
foreach ($tour_from as $key => $value) {
$chunk = array_chunk($value, 2);
foreach ($chunk as $key1 => $value1) {
echo $value1[$key][$key1] . ' - ' . $chunk[$key][$key1];
echo '<br/>';
}
}
I think you're overcomplicating it a bit. Why not just loop over the outer array and implode the inner array?
<?php
$tour_from = [
['Dhaka', 'Noakhali'],
['Chittagong', 'Sylhet'],
];
foreach ($tour_from as $elem) {
print implode(' - ', $elem);
print '<br>';
}
There is no need for chunking or a second loop.
One loop containing implode() will do.
Code: (Demo)
$tour_from = [
['Dhaka', 'Noakhali'],
['Chittagong', 'Sylhet']
];
foreach ($tour_from as $row) {
echo implode(' - ', $row), "\n";
}
Output:
Dhaka - Noakhali
Chittagong - Sylhet
Alternatively, if you like a functional one-liner: (Demo)
echo implode("<br>", array_map(function($row){ return implode(' - ', $row); }, $tour_from));
*The advantage to this is there is no trailing <br> on the final imploded string.
Or with fewer function calls, here is a version with array_reduce(): (Demo)
echo array_reduce($tour_from, function($carry, $row) {
return $carry .= ($carry !== null ? "<br>\n" : '') . $row[0] . ' - ' . $row[1];
});
If you want to avoid using foreach you can do the same thing with array_walk and pass by reference &$var.
$array = [
["Dhaka", "noakhali"],
["Chittagong", "Sylhet"]
];
array_walk($array, function(&$item){
$item = implode(' - ', $item);
});
print_r($array);
Output:
Array
(
[0] => Dhaka - noakhali
[1] => Chittagong - Sylhet
)
Sandbox
If you want to output it instead of modify the array you can just echo it instead or do something like implode('<br>', $array) afterwords.
OH, Yes, I found the way:
foreach ($tour_from as $key => $value) {
$chunk = array_chunk($value, 2);
foreach ($chunk as $key1 => $value1) {
echo implode(' - ', $value1);
echo '<br/>';
}
}
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
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 :)
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>";
}
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/>';
}
?>