campsjos
campsjos

Reputation: 1415

Convert multidimensional array keys to string

I have a multidimensional array like this:

$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';

And another array like:

$array2['second-first']='newvalue21';
$array2['second-third-first']='newvalue231';

And I can't get the way to walk $array1 recursively to check, in each iteration, if exist any element in $array2 with a key equivalent to the current element key and their parents converted to string.

To simplify the question, I will have enough with a function that prints something like:

// walking $array1:
first
second-first
second-second
second-third-first
second-fourth
third

Thank you.

Solution based on Clément Malet answer

function print_array_reccur ($array1, $array2, $str = '') 
{
    foreach ($array1 as $key => $val) {
        if (is_array($val)) {
            if ($str == '') {
                print_array_reccur($val, $array2, $key);
            } else {
                print_array_reccur($val, $array2, $str . '-' . $key);
            }
        } else {
            if ($str == '') {
                $result = $key;
            } else {
                $result = $str . '-' . $key;
            }
            if(isset($array2[$result]))
            {
                echo 'Found $array2['.$result.'] = ' . $array2[$result] . "\n";
            }
        }
    }
}

print_array_reccur ($array1, $array2);

/* OUTPUT:
Found $array2[second-first] = newvalue21
Found $array2[second-third-first] = newvalue231
*/

Upvotes: 0

Views: 736

Answers (1)

Clément Malet
Clément Malet

Reputation: 5090

I really didn't understand what you wanted in the very end, and what you want to achieve later on with your second array.

But since you are looking for a way to print something (glad you simplified that way), here it is :

$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';

function print_array_reccur ($array, $str = '') {

  foreach ($array as $key => $val) {
    if (is_array($val)) {
      if ($str == '') {
        print_array_reccur($val, $key);
      } else {
        print_array_reccur($val, $str . '-' . $key);
      }
    } else {
      if ($str == '') {
        echo $key . "\n";
      } else {
        echo $str . '-' . $key . "\n";
      }
    }
  }

}

print_array_reccur ($array1);

Output :

first
second-first
second-second
second-third-first
second-fourth
third

Upvotes: 1

Related Questions