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>";
}
Related
I am using Spout Excel reader to read Excel files from php code and saving into a multidimensional array in PHP variable,Array looks like this
$array = [
[
'id[0]' => 'BX-78',
'Name[0]' => 'XXX',
'Address[0]' => 'YUUSATD'
],
[
'id[1]' => 'BX-79',
'Name[1]' => 'YYY',
'Address[1]' => 'DHJSHDJGY'
],
[
'id[2]' => 'BX-80',
'Name[2]' => 'ZZZ',
'Address[2]' => 'DDSDSDA'
]
[
'id[3]' => 'BX-78',
'Name[3]' => 'AAA',
'Address[3]' => 'FSDSDS'
][
'id[4]' => 'BX-81',
'Name[4]' => 'XXX',
'Address[4]' => 'DSDSDSD'
]];
Now i want to show duplicate data from above array using two keys ['id'] and ['name'] if id repeats show as duplicate data,
If name repeats show that row as duplicate data if both are duplicate show as again duplicate row
Otherwise it is unique row.
I have tried using multidimensional array sorting but it is using only one key to match data in rows.
foreach ($arrExcelData as $v) {
if (isset($arrExcelData[$v[0]])) {
// found duplicate
continue;
}
// remember unique item
$arrExcelData3[$v[0]] = $v;
}
// if you need a zero-based array, otheriwse work with $_data
$arrExcelData2 = array_values($arrExcelData3);
Edited : Expected Output Result :
Matching Rows:
Id Name Address
-------------------------
BX-78 XXX YUUSATD
BX-78 AAA DDSDSDA
BX-81 XXX DSDSDSD`
If you want to list the duplicate values, I think the address of the second match should be FSDSDS as there is not item with name AAA and value DDSDSDA:
BX-78 AAA FSDSDS
If that is the case, what you could do is to first use a double foreach to mark the arrays that contain a duplicate id or name by for example adding a property named id and name except when the array is itself in the second loop.
After this loop, you can tell which arrays are the duplicate ones. Instead of using a corresponding index 0 as in id[0], I have used reset and next so it is not tied to these indexes.
To get the filtered result you could use array_reduce to check for the array keys and unset them.
For example:
foreach ($array as $index => $a) {
foreach ($array as $v) {
if ($v === $a) continue;
if (reset($v) === reset($a)) $array[$index]["id"] = "duplicate";
if (next($v) === next($a)) $array[$index]["name"] = "duplicate";
}
}
$array = array_reduce($array, function($carry, $item) {
if (array_key_exists("id", $item) || array_key_exists("name", $item)) {
unset($item["id"], $item["name"]);
$carry[] = $item;
}
return $carry;
}, []);
print_r($array);
Result
Array
(
[0] => Array
(
[id[0]] => BX-78
[Name[0]] => XXX
[Address[0]] => YUUSATD
)
[1] => Array
(
[id[3]] => BX-78
[Name[3]] => AAA
[Address[3]] => FSDSDS
)
[2] => Array
(
[id[4]] => BX-81
[Name[4]] => XXX
[Address[4]] => DSDSDSD
)
)
See a php demo
I've this very pragmatic approach:
$spout_output = [
[
'id[0]' => 'BX-78',
'Name[0]' => 'XXX',
'Address[0]' => 'YUUSATD'
],
[
'id[1]' => 'BX-79',
'Name[1]' => 'YYY',
'Address[1]' => 'DHJSHDJGY'
],
[
'id[2]' => 'BX-80',
'Name[2]' => 'ZZZ',
'Address[2]' => 'DDSDSDA'
],
[
'id[3]' => 'BX-78',
'Name[3]' => 'AAA',
'Address[3]' => 'FSDSDS'
],
[
'id[4]' => 'BX-81',
'Name[4]' => 'XXX',
'Address[4]' => 'DSDSDSD'
]];
// store id to row, and name to row mappings.
// id and name will be keys, value will be an array of indexes of the array $spout_output
$id_to_rows = array();
$name_to_rows = array();
$duplicate_ids = array();
$duplicate_names = array();
foreach($spout_output as $row => $data)
{
$key_id = 'id['.$row.']';
$key_name = 'Name['.$row.']';
if(!isset($data[$key_id]))
continue;
$value_id = $data[$key_id];
$value_name = $data[$key_name];
if(!isset($id_to_rows[$value_id]))
{
$id_to_rows[$value_id] = array();
}
else
{
if(!isset($duplicate_ids[$value_id]))
{
$duplicate_ids[$value_id] = $id_to_rows[$value_id];
}
$duplicate_ids[$value_id][] = $row;
}
if(!isset($name_to_rows[$value_name]))
{
$name_to_rows[$value_name] = array();
}
else
{
if(!isset($duplicate_names[$value_name]))
{
$duplicate_names[$value_name] = $name_to_rows[$value_name];
}
$duplicate_names[$value_name][] = $row;
}
$id_to_rows[$value_id][] = $row;
$name_to_rows[$value_name][] = $row;
}
echo 'Duplicates:';
echo '<br>';
$shown_rows = array();
foreach($duplicate_ids as $id => $rows)
{
foreach($rows as $nr)
{
echo $id . '|' . $spout_output[$nr]['Name['.$nr.']'] . '|' . $spout_output[$nr]['Address['.$nr.']'];
echo '<br>';
$shown_rows[] = $nr;
}
}
foreach($duplicate_names as $name => $rows)
{
foreach($rows as $nr)
{
// if already shown above, skip this row
if(in_array($nr, $shown_rows))
continue;
echo $spout_output[$nr]['id['.$nr.']'] . '|' . $spout_output[$nr]['Name['.$nr.']'] . '|' . $spout_output[$nr]['Address['.$nr.']'];
echo '<br>';
$shown_rows[] = $nr;
}
}
Outputs:
Duplicates:
BX-78|XXX|YUUSATD
BX-78|AAA|FSDSDS
BX-81|XXX|DSDSDSD
I think your 'wanted output' contains an error in the address?
Anyway, with my code above I think you'll have enough mapped data to produce the output you want.
You could do something like this:
$dupes = [];
$current = [];
foreach ($array as $index => $entry) {
$idKey = "id[$index]";
$nameKey = "Name[$index]";
if (array_key_exists($entry[$idKey], $current)) {
$dupes[] = [$entry, $current[$entry[$idKey]]];
}
elseif (array_key_exists($entry[$nameKey], $current)) {
$dupes[] = [$entry, $current[$entry[$nameKey]]];
}
else {
$current[$entry[$idKey]] = $current[$entry[$nameKey]] = $entry;
}
}
print_r($dupes);
Which results in an array containing each set of duplicates (array of arrays):
Array
(
[0] => Array
(
[0] => Array
(
[id[3]] => BX-78
[Name[3]] => AAA
[Address[3]] => FSDSDS
)
[1] => Array
(
[id[0]] => BX-78
[Name[0]] => XXX
[Address[0]] => YUUSATD
)
)
[1] => Array
(
[0] => Array
(
[id[4]] => BX-81
[Name[4]] => XXX
[Address[4]] => DSDSDSD
)
[1] => Array
(
[id[0]] => BX-78
[Name[0]] => XXX
[Address[0]] => YUUSATD
)
)
)
Demo here: https://3v4l.org/JAtNU
In case someone of you are searching unique values by key.
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
This function just takes multidimensional array and key value of field you need.
Then takes value of given array one by one (smaller arrays).
Then traverses given array and looking if taken key-value pair matches with given key.
After that if taken key-value pair matches with given key function just inserts smaller array in temporary array (array with unique values).
Don't forget to increment indexes of arrays ($i).
Then return array you got (with unique values) after function ends work.
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 :)
Hello guys just want to ask how can I put an associative array in csv?
For example if I have an array like this.
Array
(
[0] => Array
(
[restaurant_id] => 1227
[new_lat] => 13.62241
[new_long] => 123.19341
[date_updated] => 2013-11-14 11:20:26
)
[1] => Array
(
[restaurant_id] => 1218
[new_lat] => 14.66732
[new_long] => 121.02618
[date_updated] => 2013-11-14 11:22:22
)
)
For my code in generating csv is this:
$restaurant_id = $post_data['company_id'];
$new_lat_entry = $post_data['new_lat'];
$new_long_entry = $post_data['new_long'];
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
$data = unserialize(file_get_contents('addresses.txt'));
$data[] = $data_add;
$serialize_data = serialize($data);
file_put_contents("addresses.txt", $serialize_data, LOCK_EX); //write the text file
$array = unserialize(file_get_contents('addresses.txt')); //THIS WILL GET THE ARRAY
echo "<pre>";
print_r($array); //display it
$csv = '';
foreach($array as $row) {
$csv .= implode(',', $row) . "\n";
}
//fn_print_die($csv);
$file_input = fopen("addresses.csv","w");
foreach($csv as $line){
fputcsv($file_input,split(',',$line));
}
fclose($file_input);
This should work...
<?php
foreach ($array as $row) {
fputcsv($file_input, $row);
}
fclose($file_input);
?>
Just refer to the fputcsv manual on php.net
You should try to implement SPL classes when possible:
$csv_file = new SplFileObject('addresses.csv', 'w');
foreach ($address_list as $address_fields) {
$csv_file->fputcsv($address_fields);
}
You can use implode to do something like this pretty easily
$csv = '';
foreach($array as $row) {
$csv .= implode(',', $row) . "\n";
}
To make this clean, you would have to
collect all keys from the array (foreach twice)
build a second array with each restaurant (no subnodes)
merge the keys array into that and THEN
merge all restaurant subnodes to those keys.
The reason is simple: restaurant A has "[self_service] => true"
The CSV line for restaurant B will either miss a column or worse, have "[vegetarian_food] => false" instead.
In the end, you would have "true" and "false" in the same column under each other, with theo first meaning "Yes, self service" and the second meaning "Sorry veggies". You will probably never notice, because they might still have the same count(array).
(I would write this as a comment, but my Stack Exchange reputation does not allow me that yet (48 now, 2 more to go, yay!)
This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 6 months ago.
I'm trying to create a INSERT statement for every row in a PHPExcel object. As I've struggled to iterate across the column (ie. go B1 C1 D1, get the values, and put them into an array), I've opted to get all the values for each column and put them into a multi-dimensional array that looks like this:
Array
(
[foo] => Array
(
[0] => 250
[1] => 247
[2] => 279
[3] => 249
)
[bar] => Array
(
[0] => AM PROV
[1] => AM PROV
[2] => AM PENS
[3] => AM PROV
)
[schoo] => Array
(
[0] => xxxx
[1] => yyy
[2] => zzz
[3] => aaa
)
)
I want to merge each of the arrays so that all the data at index 0 is in one array, etc. I've built a generic tool to allow you to select the columns you want from an uploaded spreadsheet. It needs to first merge the column data into a single array and then it should generate INSERT statements for each of the arrays. So the final deliverable is this:
INSERT INTO (foo, bar, schoo) VALUES (250, "AM PROV", "xxxx");
All help appreciated.
UPDATE: Hey all, thank you very much for your answers. I finally managed to get it working using row and cell iterators as per Mark's suggestion and it's working. I have a separate issue with it now, but I think it's something I can solve. Thanks again.
<?php
$uberArray = array(
"foo" => array(
0 => 250,
1 => 247,
2 => 279,
3 => 249,
),
"bar" => array(
0 => "AM PROV",
1 => "AM PROV",
2 => "AM PENS",
3 => "AM PROV",
),
"schoo" => array(
0 => "xxxx",
1 => "yyy",
2 => "zzz",
3 => "aaa",
)
);
$yourMysqlLink = mysql_connect('localhost', 'user', 'pass');
mysql_query('SET NAMES utf8'); // Adjust according to your encoding
$colNames = array_keys($uberArray);
$stringCols = array('bar', 'schoo');
$sqlInsertStr = 'INSERT INTO `your_table` (`'.implode('`, `', $colNames)."`) VALUES \n";
$rows = array();
// Not really for iterating the first array, we just need a loop
foreach ($uberArray[$colNames[0]] as $k => $v) {
$vals = array();
foreach ($colNames as $v2) {
$val = $uberArray[$v2][$k];
if (in_array($v2, $stringCols)) {
$val = "'".mysql_real_escape_string($val, $yourMysqlLink)."'";
}
$vals[] = $val;
}
$rows[] = "\t(".implode(', ', $vals).")";
}
$sqlInsertStr .= implode(",\n", $rows).';';
echo '<pre style="clear:both;">'.$sqlInsertStr.'</pre>'; ;
Note that you may need to do a few adjustments for performance reasons, if $uberArray is big (e.g. splitting the insert string into chunks). Or you can convert the data to CSV and use MySQL LOAD DATA INFILE method, which is real fast.
Not sure if this is what you were after but...
<?php
# Given this array
$arrays = array(
'foo' => array(
0 => 250,
1 => 247,
2 => 279,
3 => 249
),
'bar' => array(
0 => 'AM PROV',
1 => 'AM PROV',
2 => 'AM PENS',
3 => 'AM PROV'
),
'schoo' => array(
0 => 'xxxx',
1 => 'yyy',
2 => 'zzz',
3 => 'aaa'
)
);
# This code generates...
$fields = array();
$inserts = array();
foreach ($arrays as $k => $v) {
$fields[] = $k;
}
for ($i = 0; $i < count($arrays[$fields[0]]); $i++) {
$vals = array();
foreach ($fields as $field) {
$vals[] = $arrays[$field][$i];
}
$inserts[] = 'INSERT INTO (' . implode(',', $fields) . ') VALUES ("' . implode('","', $vals) . '")';
}
# This array
/* $inserts = array(
'INSERT INTO (foo, bar, schoo) VALUES ("250", "AM PROV", "xxxx")',
'INSERT INTO (foo, bar, schoo) VALUES ("247", "AM PROV", "yyy")',
'INSERT INTO (foo, bar, schoo) VALUES ("279", "AM PENS", "zzz")',
'INSERT INTO (foo, bar, schoo) VALUES ("249", "AM PROV", "aaa")'
); */
var_dump($inserts);
Edit: Though I think you're missing a table name from your INSERT statements.
Edit2: You could shorten the code using array_keys like Frosty Z does and skip the first foreach.
$inputArray = array('a' => array(1, 2, 3), 'b' => array("X'", 'Y', 'Z'));
$finalArray = array();
// build array with appropriate data rows
$finalIndex = 0;
foreach($inputArray as $key => $row)
{
foreach($row as $value)
$finalArray[$finalIndex][] = $value;
$finalIndex++;
}
// format it as SQL insert queries
$fields = array_keys($inputArray);
foreach($finalArray as $row)
{
echo "INSERT INTO table (".implode(", ", $fields).") "
. " VALUES (".implode(", ", array_map("format_data", $row)).");\n";
}
function format_data($value)
{
// assuming you're using MySQL. Replace the escape function by
// the appropriate one
if (is_string($value))
return "'".mysql_real_escape_string($value)."'";
else
return $value;
}
You can use one of those strange spl iterators for this :)
$iter = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
foreach ($uberArray as $colName => $colValues) {
$iter->attachIterator(new ArrayIterator($colValues), $colName);
}
foreach ($iter as $vals) {
print_r($vals);
//or $pdoStmt->execute($vals);
}
But really, a simple for loop is the tool to use here.
I see no reason to merge the array unless you feel like wasting memory. You've already probably made a copy of the data. This just inserts the data row by row.
$data = array('foo' => array(...), ... );
$fields = array('foo', 'bar', 'schoo');
$c = count($data[$fields[0]));
$base_sql = 'INSERT INTO tbl ('.implode(',', $fields).') VALUES ';
for ($i = 0; $i < $c; ++$i)
{
$row_data = array();
foreach ($fields as $field)
$row_data[] = "'".escape_func($data[$field][$i])."'";
$sql = $base_sql . '(' . implode(',', $row_data). ')';
db_query($sql);
}
I would actually use prepared statements.
And you really should try to figure out how to iterate through the original dataset in one pass.
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/>';
}
?>