从Controller中的数组获取数据

时间:2019-12-07 14:13:41

标签: arrays laravel

我在Contoller中具有功能

<canvas id="canvas" width="600px" height="600px"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var stepWidthFactor = 200;
        var mouseX, mouseY;
        function background() {
            ctx.fillStyle = "#505050";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        }
        var ball = {
            x: 100,
            y: 100,
            dx: 0,
            dy: 0,
            draw: function () {
              ctx.fillStyle = "#F00000";
              ctx.beginPath();
              ctx.arc(this.x, this.y, 30, 0, 2 * Math.PI);
              ctx.fill();
              ctx.stroke();
            }
        }
        
        function draw() {
          background();
          ball.draw();
          
          var shouldMove = Math.abs(ball.x - mouseX) > 1 || Math.abs(ball.y - mouseY) > 1;
                          
          if(shouldMove) {
            ball.x += ball.dx;
            ball.y += ball.dy;
          } else {
            ball.dx = 0;
            ball.dy = 0;
          }
            
          window.requestAnimationFrame(draw)
        }
        
        document.addEventListener("click", function (e) {
            mouseX = e.clientX;
            mouseY = e.clientY;
            ball.dx = (ball.x - mouseX) / stepWidthFactor * -1;
            ball.dy = (ball.y - mouseY) / stepWidthFactor * -1;
        })
        
        draw();
    </script>

我在入门班也有

public function dataCountry()
    {
        $this->country = array(
            1 =>    'Serbia',
            2 =>    'USA',
            3 =>    'Croatia',
            4 =>    'Russia',
            5 =>    'China'
        );
    }

所以我有sql查询,其中我正在从数据库中调用一些信息。我的结果是

$this->country = array();

我在哪里得到这样的结果:

$item->country

那么我该如何更改或影响要替换的结果,并在结果之间添加“,”。我将在查看之前执行此操作,我将更改$ item-> country =“ 从国家/地区替换”。但是我不知道该怎么做。

请帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

这应该对您有用:

public function dataCountry()
{
    $this->country = array(
        1 =>    'Serbia',
        2 =>    'USA',
        3 =>    'Croatia',
        4 =>    'Russia',
        5 =>    'China'
    );

    //after database query you end up with
    $item->country = "1,4";

    $item->country = explode(",", $item->country);

    for($i=0; $i < count($item->country); $i++) {
        $index = $item->country[$i];

        if( !empty($this->country[$index]) ) {
            $item->country[$i] = $this->country[$index];
        }
    }

    $item->country = implode(",", $item->country);

    echo $item->country;
    // Should output: Serbia,Russia
}