39411

Iterate through every single key and value in a multi-dimensional associative array PHP

Question:

I have just learned about key/value pairs.

I tried looking for an existing answer and tried to understand what I could about key/value pairs and associative arrays. Though this is becoming a little too time-consuming.

I am having troubles figuring out how to iterate through this multi-dimensional associative array without getting any errors.

$arr = array( 'test1' => array( 'testing 1-1' => array('testing 1-1-1', 'testing 1-1-2', 'testing 1-1-3'), 'testing 1-2' => array('testing 1-2-1', 'testing 1-2-2', 'testing 1-2-3'), 'testing 1-3' => array('testing 1-3-1', 'testing 1-3-2', 'testing 1-3-3')), 'test2' => array( 'testing 2-1' => array('testing 2-1-1', 'testing 2-1-2', 'testing 2-1-3'), 'testing 2-2' => array('testing 2-2-1', 'testing 2-2-2', 'testing 2-2-3'), 'testing 2-3' => array('testing 2-3-1', 'testing 2-3-2', 'testing 2-3-3')), 'test3' => array( 'testing 3-1' => array('testing 3-1-1', 'testing 3-1-2', 'testing 3-1-3'), 'testing 3-2' => array('testing 3-2-1', 'testing 3-2-2', 'testing 3-2-3'), 'testing 3-3' => array('testing 3-3-1', 'testing 3-3-2', 'testing 3-3-3')));

So I know print_r does the job perfectly fine rendering the whole array but what I am trying to achieve is to be able to grab every key and value possible.

I try to echo all the strings 1 by 1 through foreach loops but it seems that the word array itself causes an error somehow. I believe this is my most logical approach to it.

foreach ($arr as $test) { echo $test . '<br>'; foreach ($test as $testing1) { echo '&nbsp&nbsp' . $testing1 . '<br>'; foreach ($testing1 as $testing2) { echo '&nbsp&nbsp&nbsp&nbsp' . $testing2 . '<br>'; } } }

Though it will result into the following:

Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 88 Array Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 1-1-1 testing 1-1-2 testing 1-1-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 1-2-1 testing 1-2-2 testing 1-2-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 1-3-1 testing 1-3-2 testing 1-3-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 88 Array Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 2-1-1 testing 2-1-2 testing 2-1-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 2-2-1 testing 2-2-2 testing 2-2-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 2-3-1 testing 2-3-2 testing 2-3-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 88 Array Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 3-1-1 testing 3-1-2 testing 3-1-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 3-2-1 testing 3-2-2 testing 3-2-3 Notice: Array to string conversion in /opt/lampp/htdocs/projects/form/phptest.php on line 90 Array testing 3-3-1 testing 3-3-2 testing 3-3-3

So I'd like to know if there is something that I am missing or is this not possible to achieve?

UPDATE: Thanks for the answers.

This is the code I used based on the answers I got:

foreach ($arr as $k => $test) { echo $k . '<br>'; foreach ($test as $k1 => $testing1) { echo '&nbsp&nbsp' . $k1 . '<br>'; foreach ($testing1 as $k2 => $testing2) { echo '&nbsp&nbsp&nbsp&nbsp' . $testing2 . '<br>'; } } }

UPDATE:

I really like HoldOffHunger's suggestion.

<?php // Your Array Here $arr = [...]; // IterateArray() function function IterateArray($data) { if(is_array($data)) { foreach ($data as $data_key => $data_value) { print("\n\n"); print($data_key . ' :: '); print(IterateArray($data_value)); } } else { print($data); print("\n"); } } // Call IterateArray() IterateArray($arr); ?>

Unfortunately, I had no use for this recursive function. Hard coding each instance of loop lets me do different things for each nesting loop. Though (and correct me if I'm wrong) this will be useful if each dimension of a multi-dimensional array were to repeat the same code.

Answer1:

<a href="http://php.net/manual/en/control-structures.foreach.php" rel="nofollow">The foreach statement</a> has the option of iterating over just the values, as you're doing, or the keys and values. I suspect this is what you're looking for:

foreach ($arr6 as $k=>$test) { echo $k . '<br>'; foreach ($test as $k1=>$testing1) { echo '&nbsp&nbsp' . $k1 . '<br>'; foreach ($testing1 as $k2=>$testing2) { echo '&nbsp&nbsp&nbsp&nbsp' . $testing2 . '<br>'; } } }

The notices you're getting are because you're trying to use echo on an array, which is not possible.

Answer2:

welcome to stackoverflow. Those things are Notices, you should not use echo with arrays, instead use print_r($ar) or var_dump($ar)

foreach ($arr6 as $test) { print_r($test); foreach ($test as $testing1) { print_r($testing1); foreach ($testing1 as $testing2) { print_r($testing2); } } }

You can also print keys like this:

foreach ($arr6 as $mykey => $test) { echo $mykey; print_r($test);

Answer3:

$arr = array( 'test1' => array( 'testing 1-1' => array('testing 1-1-1', 'testing 1-1-2', 'testing 1-1-3'), 'testing 1-2' => array('testing 1-2-1', 'testing 1-2-2', 'testing 1-2-3'), 'testing 1-3' => array('testing 1-3-1', 'testing 1-3-2', 'testing 1-3-3')), 'test2' => array( 'testing 2-1' => array('testing 2-1-1', 'testing 2-1-2', 'testing 2-1-3'), 'testing 2-2' => array('testing 2-2-1', 'testing 2-2-2', 'testing 2-2-3'), 'testing 2-3' => array('testing 2-3-1', 'testing 2-3-2', 'testing 2-3-3')), 'test3' => array( 'testing 3-1' => array('testing 3-1-1', 'testing 3-1-2', 'testing 3-1-3'), 'testing 3-2' => array('testing 3-2-1', 'testing 3-2-2', 'testing 3-2-3'), 'testing 3-3' => array('testing 3-3-1', 'testing 3-3-2', 'testing 3-3-3'))); foreach ($arr as $key=>$val){ echo $key; foreach($val as $k=>$v){ echo $k; foreach($v as $ku=>$vu){ echo $ku; } } }

you are echoing array not string.

Answer4:

Welcome to SO!

I would like to post a solution that works for any-type of array, whether it is 3-d, 4-d, or any dimension. So, why not <em>recursion</em>, foreach(), and is_array()?

<a href="https://ideone.com/duoXn3" rel="nofollow">IDEOne: Online Demo/Sandox of IterateArray()</a>

<?php // Your Array Here $arr = [...]; // IterateArray() function function IterateArray($data) { if(is_array($data)) { foreach ($data as $data_key => $data_value) { print("\n\n"); print($data_key . ' :: '); print(IterateArray($data_value)); } } else { print($data); print("\n"); } } // Call IterateArray() IterateArray($arr); ?>

IterateArray() here will print the data if it's not an array, and otherwise, it will iterate over the elements of the array, and call IterateArray() on these elements.

The nice part about this solution: if your data structure changes, your function won't have to!

Recommend

  • Django-tastypie pass request.user to custom save method
  • How to Dynamically Remove component in ComponentResolveFactory
  • Need help for combining two regex conditions using something like AND operator
  • Reducing memory requirements for convolutional neural network
  • Should authentication be in a separate service for wcf?
  • Inject Javascript code into a web page
  • How to do a partial merge in git?
  • Rails - Use a class method from a another class method with one attribute of the second class
  • Cannot select Infragistics controls in WinForms designer
  • Using simplemodal with wordpress
  • svnserve and SASL problem
  • Can't perform CORS request using Angularjs
  • Retrieving Application's DisplayName/UninstallString from Registry Using Powershell
  • Winston logger not write to file
  • Parallelization via JDBC - Pyspark - How does parallelization work using JDBC?
  • jQuery how to translate livequery to on?
  • Identifying dates in strings using NLTK
  • Enable CORS on Tomcat 8.0.30
  • VS2010: Ctrl-PgUp / -PgDown like in browsers
  • How to get File path from pdfUri obtained from PDF chooser intent library, in onActivityResult call
  • Auto send email based on the time and email address in database
  • Defer unused CSS
  • Add checkbox dynamically using angular 2
  • Set SelectedIndex of ListView in FlipView_SelectionChanged event
  • How to redirect into different page by user type in php and mysql
  • Generate and export point cloud from Project Tango
  • Stop an element moving with padding on hover
  • Ajax call on Multiple selection in Select box
  • Year over Year Stats from a Crossfilter Dataset
  • Ruby regex for matching simpliest Ruby's regexes
  • Why is ordered choice in pyparsing failing for my use case?
  • Google App Engine Datastore: Dealing with eventual consistency
  • Bad automatic Triangulation with Mayavi for coloring a surface known only by its corner
  • How to use FirstOrDefault inside Include
  • PHP Permalinks.. how to change?
  • Running R's aov() mixed effects model from Python using rpy2
  • No OpKernel was registered to support Op 'Conv2D' with these attrs
  • ReferenceError: TextEncoder is not defined