phparraysarray-mergearray-reduce

Reduce not work correctly i need add exeption / exlusion


i have an array like that in $_POST var; but need know that in some cases the array is a hugge multilevel from json:

array (
  'idprocess' => 'f-gen-dato1',
  'idform' => 'f-gen-dato2',
)

OR:

array (
  array (
    'idprocess1' => 'f-gen-dato1',
    'idform1' => 'f-gen-dato2',
  ),
  array (
    'idprocess2' => 'f-gen-dato1',
    'idform2' => 'f-gen-dato2',
  )
)

i try to reduce; any arrays with this:

public function ReduARR($Var) {
        $result = $Var;
        if (is_array($Var)) {
            $result = array_reduce($Var, 'array_merge', array());
        }
        return $result;
    }

but i need avoid the array i show you... frist or single level. and work only in the second or multilevel.

i get this error with one lvl:

array_merge(): Argument #2 is not an array

Solution

  • My guess is that you wish to merge or reduce some arrays, and you might be trying to write some functions similar to:

    $arr1 = array(
        'idprocess1' => 'f-gen-dato1',
        'idform1' => 'f-gen-dato2',
    );
    
    $arr2 = array(
        'idprocess2' => 'f-gen-dato1',
        'idform2' => 'f-gen-dato2',
    );
    
    function finalArray($arr1, $arr2)
    {
        if (is_array($arr1) && is_array($arr2)) {
            return mergeTwoArrays($arr1, $arr2);
        }
    }
    
    function mergeTwoArrays($arr1, $arr2)
    {
        return array_merge($arr1, $arr2);
    }
    
    var_dump(finalArray($arr1, $arr2));
    

    for instance.


    $arr = array(
        array(
            'idprocess1' => 'f-gen-dato1',
            'idform1' => 'f-gen-dato2',
        ),
        array(
            'idprocess2' => 'f-gen-dato1',
            'idform2' => 'f-gen-dato2',
        ),
    );
    
    if (is_array($arr[0]) && is_array($arr[1])) {
        var_dump(array_merge($arr[0], $arr[1]));
    }
    

    Output

    array(4) {
      ["idprocess1"]=>
      string(11) "f-gen-dato1"
      ["idform1"]=>
      string(11) "f-gen-dato2"
      ["idprocess2"]=>
      string(11) "f-gen-dato1"
      ["idform2"]=>
      string(11) "f-gen-dato2"
    }