【问题标题】:Reduce not work correctly i need add exeption / exlusion减少无法正常工作我需要添加异常/排除
【发布时间】:2019-10-30 02:00:52
【问题描述】:

我在 $_POST var 中有一个类似的数组;但需要知道,在某些情况下,数组是来自 json 的一个巨大的多级:

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

或者:

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

我尽量减少;任何带有这个的数组:

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

但我需要避免我向您展示的数组...第一级或单级。并且只在第二级或多级工作。

我得到一个 lvl 的这个错误:

array_merge(): Argument #2 is not an array

【问题讨论】:

标签: php arrays array-merge array-reduce


【解决方案1】:

我的猜测是您希望合并或减少一些数组,并且您可能正在尝试编写一些类似的函数:

$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));

例如。


$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]));
}

输出

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"
}

【讨论】:

  • 真正我要减少的变量数组是$_POST
  • 不,我需要减少数组...因为索引 0 和 1 无效...您可以看到示例...脚本和错误...
  • 与您的输出相同,但在单个 lvl 数组中出现错误,我需要避免它
猜你喜欢
  • 2015-05-06
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多