Echo a multidimensional array in PHP - php

I have a multidimensional array and I'm trying to find out how to simply "echo" the elements of the array. The depth of the array is not known, so it could be deeply nested.
In the case of the array below, the right order to echo would be:
This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment
This is the array I was talking about:
Array
(
[0] => Array
(
[comment_id] => 1
[comment_content] => This is a parent comment
[child] => Array
(
[0] => Array
(
[comment_id] => 3
[comment_content] => This is a child comment
[child] => Array
(
[0] => Array
(
[comment_id] => 4
[comment_content] => This is the 2nd child comment
[child] => Array
(
)
)
)
)
)
)
[1] => Array
(
[comment_id] => 2
[comment_content] => This is another parent comment
[child] => Array
(
)
)
)

<pre>
<?php print_r ($array); ?>
</pre>

It looks like you're only trying to write one important value from each array. Try a recursive function like so:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['comment_content'] . "\n";
RecursiveWrite($vals['child']);
}
}
You could also make it a little more dynamic and have the 'comment_content' and 'child' strings passed into the function as parameters (and continue passing them in the recursive call).

Proper, Better, and Clean Solution:
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach ($array as $key => $value)
{
if (is_array($value))
{
Self::traverseArray($value); // Or
// traverseArray($value);
}
else
{
echo $key . " = " . $value . "<br />\n";
}
}
}
You simply call in this helper function traverseArray($array) in your current/main class like this:
$this->traverseArray($dataArray); // Or
// traverseArray($dataArray);
source: http://snipplr.com/view/10200/recursively-traverse-a-multidimensional-array/

print_r($arr) usually gives pretty readable result.

if you wanted to store it as a variable you could do:
recurse_array($values){
$content = '';
if( is_array($values) ){
foreach($values as $key => $value){
if( is_array($value) ){
$content.="$key<br />".recurse_array($value);
}else{
$content.="$key = $value<br />";
}
}
}
return $content;
}
$array_text = recurse_array($array);
Obviously you can format as needed!

There are multiple ways to do that
1) - print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
//-------------------------------------------------
2) - use var_dump($array) to get more information of the content in the array like datatype and length.
//-------------------------------------------------
3) - you can loop the array using php's foreach(); and get the desired output.
function recursiveFunction($array) {
foreach ($array as $val) {
echo $val['comment_content'] . "\n";
recursiveFunction($vals['child']);
}
}

Try to use var_dump function.

If you're outputting the data for debugging and development purposes, Krumo is great for producing easily readable output. Check out the example output.

Recursion would be your answer typically, but an alternative would be to use references. See http://www.ideashower.com/our_solutions/create-a-parent-child-array-structure-in-one-pass/

Related

How to get all values from an array

I have an varible that retrive and stores values in an array format. That is
$fold_location = Input::get('location');
If we Print this means it look like below:
Array ( [0] => 1 [1] => 2 )
What i want is to get all values from this variable.
i am trying the following.
foreach($fold_location as $value) {
$fold_location = $value;
print_r($fold_location);
}
But it return the output as 1.
I want to get all the values. How to do that in php -mysql
You do override your Array in the loop. Try:
foreach($array as $item) print_r($item);
See also http://php.net/manual/en/control-structures.foreach.php
You can get the Array values using the PHP's array_values() function. You need not do a foreach()
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
Output of the above code will be
Array
(
[0] => XL
[1] => gold
)
Replace your foreach loop with below code.
foreach($fold_location as $value) {
echo $value;
}

PHP Array element to string

I use PHPExcel to put elements of my Excel file into an array. I then do
print_r($worksheets);
Where $worksheets is the array created through PHPExcel. The output is
Array (
[enquiry] => Array (
[0] => Array (
[0] => 86.141.247.93
)
[1] => Array (
[0] => 188.141.76.143
)
[2] => Array (
[0] => 2.29.20.161
)
)
)
What I need to do is pass each of these IPs as a String to a function. So what I am trying is this
foreach($worksheets as $ip) {
$count = 0;
if ($SpamProtecter->CheckIP($ip[$count][0])) {
print_r("SPAM");
} else {
print_r("GOOD");
}
$count++;
}
The problem I have is that it only prints out one result. How can I pass each array element as a String to CheckIP?
Thanks
You have an intermediate level in your array. Remember, foreach iterates over the top level of elements. You have 3 tiers here
foreach($worksheets['enquiry'] as $ip) { //iterate tier 1
if ($SpamProtecter->CheckIP($ip[0])) { //grab tier 3
print_r("SPAM");
} else {
print_r("GOOD");
}
}
Your $worksheets array only has a single key: enquiry, which is why you're only getting a single result output. Try this:
foreach($worksheets['enquiry']) as $ip) {
if($SpamProtector->CheckIP($ip[0]) {
// ...
I think you can also get rid of that inner $count variable since it is not used anymore.
This could work
foreach($worksheets['enquiry'] as $ip) {
if ($SpamProtecter->CheckIP($ip[0])) {
print_r("SPAM");
} else {
print_r("GOOD");
}
}
array_walk works well in situtations where you want to perform an action on each element in an array.
array_walk($worksheets["enquiry"],
function ($a) use ($SpamProtecter) {
echo $SpamProtecter->CheckIP($a[0])?"GOOD":"BAD";
});

wordpress $wpdb select results to an array

$wp->get_results will return an array and formats the array depends if the second parameter is specified; if not, it is default to an object, right? But my question is it possible to retrieve results then store it the an array? Like this $arr = array(1,2,3,4,5)? What my main concern is this.. I want to search in the array if the value is present.
Now I can't do a in_array if the returned results is like this.
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
Any help would be much appreciated. Thanks.
EDITED
my $arr would look like this
Array ( [0] => stdClass Object ( [code] => 8 [id] => ) [1] => stdClass Object ( [code] => 1 [id] => ) )
EDITED
Found a solution:
if (in_array(array('1'), $arr) {
// found value
}
You can not match directly, for matching, it you will have to do something like this :
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
foreach($arr as $newar)
{
if (in_array('2',$newar))
{
echo 'hello';
}
}
I'm not really following the problem here, but assuming you want to find a specific value inside the wpdb results......
foreach($arr as $key => $row) {
if($row->code == $VALUE_YOU_WANT_TO_MATCH) {
// do something
break;
}
}
Note: $arr is an array of objects, its not a multidimensional array.
say for example I want to check if if code = 1 exist in my result.
foreach($arr as $myarr){
if ($myarr->code == "1"){
echo "record was found\n";
break;//this line makes the foreach loop end after first success.
}
}

Create multidimensional array from standard array

Most likely I'm doing this wayyyyyy too complicated. But I'm in the need of converting multiple arrays to multidimensional array key's. So arrays like this:
Array //$original
(
[0] => 500034
[1] => 500035 //these values need to become
//consecutive keys, in order of array
)
Needs to become:
Array
(
[50034][50035] => array()
)
This needs to be done recursively, as it might also require that it becomes deeper:
Array
(
[50034][50036][50126] => array() //notice that the numbers
//aren't necessarily consecutive, though they are
//in the order of the original array
)
My current code:
$new_array = array();
foreach($original as $k => $v){ //$original from first code
if((gettype($v) === 'string' || gettype($v) === 'integer')
&& !array_key_exists($v, $original)){ //check so as to not have illigal offset types
$new_array =& $original[array_search($v, $original)];
echo 'In loop: <br />';
var_dump($new_array);
echo '<br />';
}
}
echo "After loop <br />";
var_dump($new_array);
echo "</pre><br />";
Gives me:
In loop:
int(500032)
In loop:
int(500033)
After loop
int(500033)
Using this code $new_array =& $original[array_search($v, $original)]; I expected After loop: $new_array[50034][50035] => array().
What am I doing wrong? Been at this for hours on end now :(
EDIT to answer "why" I'm trying to do this
I'm reconstructing facebook data out of a database. Below is my own personal data that isn't reconstructing properly, which is why I need the above question answered.
[500226] => Array
(
[own_id] =>
[entity] => Work
[name] => Office Products Depot
[500227] => Array
(
[own_id] => 500226
[entity] => Employer
[id] => 635872699779885
)
[id] => 646422765379085
)
[500227] => Array
(
[500228] => Array
(
[own_id] => 500227
[entity] => Position
[id] => 140103209354647
)
[name] => Junior Programmer
)
As you can see, the ID [500227] is a child of [500226], however, because I haven't got the path to the child array, a new array is created. The current parentage only works to the first level.
[own_id] is a key where the value indicates which other key should be its parent. Which is why the first array ([500226]) doesn't have a value for [own_id].
If you want to do something recursively, do it recursively. I hope that's what you meant to do.
public function pivotArray($array, $newArray)
{
$shifted = array_shift($array);
if( $shifted !== null )
{
return $this->pivotArray($array, array($shifted=>$newArray));
}
return $newArray;
}
$array = array(432, 432532, 564364);
$newArray = $this->pivotArray($array, array());
Edit: After the question's edit it doesn't seem to be very relevant. Well, maybe someone will find it useful anyway.

How to not echo array if previous one's key has been echoed already

This is what I get after a print_r($myArray) (wrapped in pre) on my array.
Array
(
[0] => 203.143.197.254
[1] => not/available
)
Array
(
[0] => 40.190.125.166
[1] => articles/not/a/page
)
Array
(
[0] => 25.174.7.82
[1] => articles/not/a/page
)
How would I return or echo just the first two in this case (no regex), given the fact that I would like to only output each array whose [1] value has not been echoed before?
My list as far more entries and $myArray[1] is sometimes the same, I want to skip echoing the same thing.
I have tried array_unique but I can't get it to work as param 1 is expected to be an array.
print_r(array_unique($myArray));
This works. Didn't do a full copy paste job but hopefully you get the idea of the logic
$echoed = array();
foreach($array as $arr) {
if(!in_array($arr[1],$echoed)) {
echo $arr[1];
$echoed[] = $arr[1];
}
}
$echoedBefore = array();
print_r(array_filter($myArray, function($entry) {
global $echoedBefore;
$alreadyEchoed = in_array($entry[1], $echoedBefore);
if (!$alreadyEchoed) {
$echoedBefore[] = $entry[1];
}
return !$alreadyEchoed;
}));

Categories