Home > Back-end >  Transform array recursively with parent and children
Transform array recursively with parent and children

Time:07-01

I want to transform an array of resources that can have an infinity of children to a simple array like below. I just want to keep the information of the parent, if there is a parent. In my context, a parent is the array just above the child array.

I have this array (bigger in reality with a lof of children), but each children may have an infinity of arrays children:

$array = array (
  0 =>
    array (
      '@id' => 'Authorization',
      '@sortOrder' => '1',
      'resource' =>
        array (
          '@id' => 'Authorization2',
          '@title' => 'Authorization2',
        ),
    ),
);

And I would like to get this, recursively :

$resources = [
  0 => [
    'parent' => null,
    'resource' => 'Authorization'],
  1 => [
    'Authorization' => 'Authorization',
    'resource' => 'Authorization2']
];

I tried this and I get every single resource but I can't get parents for resources that has one:

public function array_values_recursive($array) {
    $flat = array();
    foreach($array as $key => $value) {
        if (is_array($value)) {
            $flat = array_merge($flat, $this->array_values_recursive($value));
        }
        else {
            if($key === '@id') {
                $flat[]['value'] = $value;
            }
        }
    }
    return $flat;
}

CodePudding user response:

That did the job for me, thanks @Sammitch for the idea.

    public function array_values_recursive($array, $parent = null) {
    $flat = array();
    $i = 0;
    foreach($array as $key => $value) {
        if (is_array($value)) {
            //we create a new parent
            if(array_key_exists('@id',$array)){
                $flat = array_merge($flat, $this->array_values_recursive($value, $array['@id']));
            }
            //we keep the last parent known
            else{
                $flat = array_merge($flat, $this->array_values_recursive($value, $parent));
            }
        }
        else {
            if($key === '@id') {
                if($parent){
                    $flat[$i]['value'] = $value;
                    $flat[$i]['parent'] = $parent;
                }
                else{
                    $flat[$i]['value'] = $value;
                }
                $i  ;
            }
        }
    }
    return $flat;
}
  • Related