duankezong4064 2013-07-05 15:16
浏览 17
已采纳

PHP - 如何将数组推入特定位置?

I hope I can explain my problem

I have on array(10x10) filled with 1 and 0 e.g.

0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000

Now I'd like to push another array

e.g.

11111
11111

into it on a specific position point (3,3)
I've highlighted the position in bold

0000000000
0000000000
0011111000
0011111000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000

Futhermore, if there is already a value on the field add it, so if I repeat the process the matrix will become this.

0000000000
0000000000
0022222000
0022222000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000

I hope someone can point me in the right direction. I've already played with some array functions, but I can't get it to work.

What do you suggest?

  • 写回答

3条回答 默认 最新

  • dousendun8411 2013-07-05 15:25
    关注

    Something along these lines should do it:

    /**
     * Push a small matrix into a larger matrix.
     * Note: no size restrictions are applied, if $push
     * exceeds the size of $matrix or the coordinates are
     * too large you'll get a jaggy array.
     *
     * @param array $matrix A 2D array of ints.
     * @param array $push   A 2D array <= $matrix to push in.
     * @param int   $x      The starting x coordinate.
     * @param int   $y      The starting y coordinate.
     * @return array The modified $matrix.
     */
    function matrix_push(array $matrix, array $push, $x, $y) {
        list($i, $j) = array($x, $y);
    
        foreach ($push as $row) {
            foreach ($row as $int) {
                $matrix[$i][$j++] += $int;
            }
            $i++;
            $j = $y;
        }
    
        return $matrix;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?