Skip to content

Instantly share code, notes, and snippets.

@discoverlance-com
Created November 19, 2020 08:02
Show Gist options
  • Save discoverlance-com/6fbcb74e18f70fbbc6e8936acb678e2a to your computer and use it in GitHub Desktop.
Save discoverlance-com/6fbcb74e18f70fbbc6e8936acb678e2a to your computer and use it in GitHub Desktop.
Given a multiple nested loop array,loop through the array to get and display each key and value pair.

LOOP THROUGH MULTIPLE NESTED PHP ARRAY AND PRINT OUTPUT

This gist contains a convenient script to loop through a multiple nested php array and return it in a neat and organized html format.

Basic usage

// add sample array.php file, in your case you might just need to add your
// loop variable and remove the include 'example_array.php' statement
include 'example_array.php';
include 'loop.php';

loopthrough($my_nested_array);

Loop Properties

  • my_nested_array - nested array you want to loop through passed into loopthrough function.
<?php
$my_nested_array = array(
"verified_id" => "cdYjk8945"
"Personal Information" => [
"Forename" => "Samuel",
"MiddleName" => "Franklin",
"Surname" => "Conrad",
"DOB" => "2002-09-11",
],
"Address": [
"address1" => "NY ST Philemon",
"address2" => "NY Street",
"address3" => "",
"postInformation" => [
"country" => "Ghana" => [
"region": "Accra",
"others": ""
],
"postTown" => "Accra",
"id" => 25
]
],
"Marital Status": "single",
);
?>
<?php
/*
Gist Name: Loop Through Multiple Nested PHP array and print output
Description: Given a multiple nested loop array,loop through the array to get and display each key and value pair.
Author: Lance Armah-Abraham
Author URI: https://discoverlancearmah.online/
Version: 0.1
License: MIT - http://opensource.org/licenses/mit
*/
/**
* function to loop through each array and return the key and checkforloop function
* @param array $my_arr Nested looping array
*/
function loopthrough($my_arr) {
foreach($my_arr as $key => $val) {
echo "h1>".htmlspecialchars($key)."</h1>";
checkLoop($val);
}
}
/**
* function to loop through each child array, purpose is to have the child arrays in smaller case with h3 instead of h1 in the main loop
* @param array $new_arr Child array
*/
function childloopthrough($new_arr) {
foreach($new_arr as $key => $val) {
echo "<h3>".htmlspecialchars($key)."</h3>";
checkLoop($val);
}
}
/**
* function to check if the data passed is array or string and then return string if it's string or return the childloop if not string
*@param array $data Array returned from child or main loopthrough array
*/
function checkLoop($data) {
if(is_array($data)) {
childloopthrough($data);
} else {
echo "<p>".htmlspecialchars($data)."</p>";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment