0

I am stuck...

I have this value in my PHP:

$arr['something1']['something2'] = value;

I want to have a func($arr) that returns:

$arr['something1[something2]'] = value;

Here is my current codes for nested 3 arrays:

static function flattenArray(array $notFlat, string $pK) {
  $index = 0;

  foreach ($notFlat as $k => $v) {
    if (is_array($v)) {
      foreach ($v as $_k => $_v) {
        if (is_array($_v)) {
          foreach ($_v as $__k => $__v) {
            if (is_array($__v)) {}
            else{
              unset($notFlat[$k]);
              $newArray = array_slice($notFlat, 0, $index, true) +
                $notFlat[$k] = [$pK.$k.'['.$_k.']'.'['.$__k.']' => $__v] +
                array_slice($notFlat, $index, NULL, true);
              $notFlat = $newArray;
            }
          }
        }
      }
    }
    $index ++;
  }

  return $notFlat;
}

But that is too manual... I think recursive function can work but I am not sure what to return in case iterated value is an array.

EDIT1: Expected Output

$asd = ['asd' => ['jkf' => ['qwe' => 'wer', 'asd' => '123', 'kjk' => 'sdf', '456' => 'zxc']], 'dfg', 'test' => ['ert' => '234'], 'cvf'];

print_r(func($asd));

/*
Array
(
    [test[ert]] => 234
    [asd[jkf][456]] => zxc
    [asd[jkf][kjk]] => sdf
    [asd[jkf][asd]] => 123
    [asd[jkf][qwe]] => wer
    [0] => dfg
    [1] => cvf
)
*/
notalentgeek
  • 4,939
  • 11
  • 34
  • 53

2 Answers2

0
function flattenArray(array $notFlat) {
  function _flattenArray(&$arrayRoot, $arrayCurr, $kS) {
    foreach ($arrayCurr as $k => $v) {
      if (is_array($v)) {
        _flattenArray($arrayRoot, $v, $kS.'['.$k.']');
      }
      else {
        $currentKey = (string) $kS.'['.$k.']';
        $arrayRoot[$currentKey] = $v;
      }
    }
  }

  foreach ($notFlat as $k => $v) {
    if (is_array($v)) {
      _flattenArray($notFlat, $v, $k);
      unset($notFlat[$k]);
    }
  }

  return $notFlat;
}
notalentgeek
  • 4,939
  • 11
  • 34
  • 53
0

Code ( https://3v4l.org/5LVii )

$asd = ['asd' => ['jkf' => ['qwe' => 'wer', 'asd' => '123', 'kjk' => 'sdf', '456' => 'zxc']], 'dfg', 'test' => ['ert' => '234'], 'cvf'];

function recurse($array,$key=''){
    static $output=[];
    foreach($array as $k=>$v){
        if(is_array($v)){
            recurse($v,$key?$key.'['.$k.']':$k);
        }else{
            $output[$key?$key.'['.$k.']':$k]=$v;
        }
    }
    return $output;
}
var_export(recurse($asd));

Output:

array (
  'asd[jkf][qwe]' => 'wer',
  'asd[jkf][asd]' => '123',
  'asd[jkf][kjk]' => 'sdf',
  'asd[jkf][456]' => 'zxc',
  0 => 'dfg',
  'test[ert]' => '234',
  1 => 'cvf',
)

There isn't much that I can explain. The snippet iterates and recurses the array, appending the keys as it recurses. static allows the reuse/build of $output.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136