Transform Multiple arrays into an array only

Asked

Viewed 381 times

1

In certain process of my system, I receive as return of a function a array of characteristics and that array may contain various information, including other information arrays with different names for each type of information. Ex:

Apartamento:
Characteristics => [
 ["external_area"]=>
    array(5) {
      [0]=> "varanda"
      [1]=> "lavanderia"
      [2]=> "piscina"
      [3]=> "muros"
      [4]=> "area_serviço"
    }
    ["bedroom"]=>
     array(12) {
      [0]=> "piso_frio"
      [1]=> "alvenaria"
      [2]=> "azulejo_teto"
      [3]=> "massa_corrida"
      }
   ]

Casa:
Characteristics => [
 ["internal_area"]=>
    array(5) {
      [0]=> "mesa de madeira"
      [1]=> "area"
    }
    ["options"]=>
     array(12) {
      [0]=> "2 andares"
      [1]=> "banheiro externo"
      }
   ]

and I need everything to stay inside an array only, for example apartment, would be:

Characeristics => [
   [0]=> "varanda"
   [1]=> "lavanderia"
   [2]=> "piscina"
   [3]=> "muros"
   [4]=> "area_serviço"
   [5]=> "piso_frio"
   [6]=> "alvenaria"
   [7]=> "azulejo_teto"
   [8]=> "massa_corrida"
]

EDIT: Remembering that I don’t know the names of arrays that comes within Characteristics

  • There may be repetitions?

  • No. Both arrays and array elements do not repeat in the same type.

4 answers

3


Once I needed it and used it this solution.

function flatten($array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

This way works independent of the number of subarrays you have and also independent of keys. Ex.: https://eval.in/671144

  • It worked perfectly. Thank you.

2

You can use the function array_walk_recursive:

array_walk_recursive($array, function ($item, $key) 
{
    global $Characeristics;
    if (! is_array( $item ) ) $Characeristics[] = $item;
});

$result = array( "Characeristics" => $Characeristics );

That is, if the value you are currently passing is not an array (it will be your feature string) it is added to a new array.

The ideone is working

1

Example of how you can do it:

$arr = array(
    0 => array(1, 2, 3),
    1 => array(4, 5, 6)
);

$rs = array();
foreach ($arr as $v) {
    $rs = array_merge($rs, array_values($v));
}
unset($arr);

print_r($rs);

Be aware that this is an example. The original question array has an extra level, however, it can solve with the same logic.

In your case it must look something like this:

$rs = array('Characteristics' => array()); // Esse array serve para guardar o resultado final

foreach ($arr['Characteristics']['external_area'] as $v) {
    //aqui mescla os valores
    $rs['Characteristics'] = array_merge($rs, array_values($v));
}
unset($arr); // Se não precisar mais desses dados, apague-os

print_r($rs);

Key names

If the name of the first key is unknown, you can get it with the key function()

$arr['a']['b'] = array();
echo key($arr['a']);
// retorna 'b'

For your specific case:

$arr['Characteristics']['external_area'] = array();
echo key($arr['Characteristics']);
// retorna 'external_area'

Implementing in sample code

$rs = array('Characteristics' => array()); // Esse array serve para guardar o resultado final

$k = key($arr['Characteristics']); // obtém o nome da primeira chave

foreach ($arr['Characteristics'][$k] as $v) {
    //aqui mescla os valores
    $rs['Characteristics'] = array_merge($rs, array_values($v));
}
unset($arr); // Se não precisar mais desses dados, apague-os

print_r($rs);
  • I have no way of knowing the name of the second level array. 'external_area' may have any name or may not exist.

  • added the answer

0

I developed a function that goes through the array and merges the array, take a look, I considered the array $characteristics as the first one you posted on the question, I hope it helps

var_dump(getAllCharacteristics($characteristics));
die;

function getAllCharacteristics($characteristics) {
    $newArray = [];
    foreach ($characteristics as $characteristic) {
        if (is_array($characteristic)) {
            $newArray = array_merge($newArray, getAllCharacteristics($characteristic));
        } else {
            $newArray[] = $characteristic;
        }
    }
    return $newArray;
}

The output of the function var_dump would be:

array(9) {
  [0]=>
  string(7) "varanda"
  [1]=>
  string(10) "lavanderia"
  [2]=>
  string(7) "piscina"
  [3]=>
  string(5) "muros"
  [4]=>
  string(13) "area_serviço"
  [5]=>
  string(9) "piso_frio"
  [6]=>
  string(9) "alvenaria"
  [7]=>
  string(12) "azulejo_teto"
  [8]=>
  string(13) "massa_corrida"
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.