duancan8382 2018-10-22 21:23
浏览 49
已采纳

用于构造数组的PHP等价的JavaScript扩展语法是什么?

Asked already a question about converting functions from Ruby to JS, and now I'm trying to implement with JS to PHP, but something does not work, tell me what I'm missing?

The code on JS:

function transpose(a) {
    return a.length === 0 ? a : a[0].map((col, i) => a.map((row) => row[i]))
}

function f(a) {
    return a.length === 0 ? [] : [...a.shift(), ...f(transpose(a).reverse())];
} 

console.log(f([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]))

In PHP do so:

function transpose($array) 
{
    if (count($array) === 0) return $array;

    foreach ($array as  $rowkey => $row)
    {
        foreach($row as $colkey => $col)
        {
            $out[$colkey][$rowkey] = $col;
        }
    }

    return $out;
}

function f($a)
{
    return (count($a) === 0) 
    ? [] 
    : [
        array_shift(...$a), 
        f(array_reverse(transpose(...$a)))
    ];
}

print_r(f([[1,2,3,4],[10,11,12,5],[9,8,7,6]]));

Is there a problem? Errors:

Warning: array_shift() expects exactly 1 parameter, 3 given in [...][...] on line 24

Invalid argument supplied for foreach() in [...][...] on line 10

Warning: Invalid argument supplied for foreach() in [...][...] on line 10

Warning: Invalid argument supplied for foreach() in [...][...] on line 10

Warning: Invalid argument supplied for foreach() in [...][...] on line 10

Notice: Undefined variable: out in [...][...] on line 16

Warning: array_reverse() expects parameter 1 to be array, null given in [...][...] on line 25 Warning: count(): Parameter must be an array or an object that implements Countable in [...][...] on line 21

</div>
  • 写回答

3条回答 默认 最新

  • dongqie4402 2018-10-22 21:34
    关注

    You don't need to use the ... operator in the PHP version. You just need to merge the shifted row with the result of the recursive call.

    function f($a)
    {
        return (count($a) === 0) 
        ? [] 
        : array_merge(
            array_shift($a), 
            f(array_reverse(transpose($a)))
        );
    }
    

    array_merge(array_shift($a), f(array_reverse(transpose($a))))
    

    is the same thing that's happening here:

    [...a.shift(), ...f(transpose(a).reverse())]
    

    ... expands the elements of the array in JS. It works similarly in PHP, but here it is only valid in function definitions or calls.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上