Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array's key recursively and create underscore separated string

Right now i got an array which has some sort of information and i need to create a table from it. e.g.

Student{
      [Address]{
              [StreetAddress] =>"Some Street"
              [StreetName] => "Some Name"
      }
      [Marks1] => 100
      [Marks2] => 50
    }

Now I want to create database table like which contain the fields name as :

Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2

It should be recursive so from any depth of array it can create the string in my format.

like image 200
Nehal Avatar asked May 01 '10 09:05

Nehal


2 Answers

You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
    // Build long key name based on parent keys
    for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
        $key = $iterator->getSubIterator($i)->key() . '_' . $key;
    }
    $keys[] = $key;
}
var_export($keys);

The above example outputs something like:

array (
  0 => 'Student_Address_StreetAddress',
  1 => 'Student_Address_StreetName',
  2 => 'Student_Marks1',
  3 => 'Student_Marks2',
)
like image 151
salathe Avatar answered Nov 14 '22 06:11

salathe


(Working on it, here is the array to save the trouble):

$arr = array
(
    'Student' => array
    (
        'Address' => array
        (
            'StreetAddress' => 'Some Street',
            'StreetName' => 'Some Name',
        ),
        'Marks1' => '100',
        'Marks2' => '50',
    ),
);

Here it is, using a modified version of @polygenelubricants code:

function dfs($array, $parent = null)
{
    static $result = array();

    if (is_array($array) * count($array) > 0)
    {
        foreach ($array as $key => $value)
        {
            dfs($value, $parent . '_' . $key);
        }
    }

    else
    {
        $result[] = ltrim($parent, '_');
    }

    return $result;
}

echo '<pre>';
print_r(dfs($arr));
echo '</pre>';

Outputs:

Array
(
    [0] => Student_Address_StreetAddress
    [1] => Student_Address_StreetName
    [2] => Student_Marks1
    [3] => Student_Marks2
)
like image 8
Alix Axel Avatar answered Nov 14 '22 07:11

Alix Axel