Exploding a list into a nested list array, and then into a multidimensional array in PHP

Today, I show you how to convert (explode) a list, in this case a list of authors, first and last names separated by a comma, into a nested list array, and then iterate through the nested list array and convert (explode) into a multidimensional array:

 

 

Exploding a list
 
<?php
$AUTHOR_NAMES = "Carlo Carandang,Mimi Carandang";
echo $AUTHOR_NAMES;
echo "\n";
// explode list into array
$AUTHOR = explode(",", $AUTHOR_NAMES);
print_r($AUTHOR);
//replace space in array list with comma
$result = str_replace(array(' '), ',', $AUTHOR);
print_r($result);
//iterate through the nested-list array, and explode each list
for ($i = 0; $i < count($result); ++$i) {
        $res[$i] = explode(",", $result[$i]);
        print_r($res[$i]);
    }
?>

OUTPUT OF THE CODE:

List of authors (string):

Carlo Carandang,Mimi Carandang

Explode into a nested list array:

Array
(
[0] => Carlo Carandang
[1] => Mimi Carandang
)

Space replaced by a comma:

Array
(
[0] => Carlo,Carandang
[1] => Mimi,Carandang
)

Iterate through the array, and explode into a multidimensional array:

Array
(
[0] => Carlo
[1] => Carandang
)
Array
(
[0] => Mimi
[1] => Carandang
)

Now you are ready to parse and analyze the data in the array!

 

photo credit: Christiaan Colen Locky ransomware: source code via photopin (license)

Leave a Comment

Your email address will not be published. Required fields are marked *

"