문제

다음 코드가 있습니다.

 $final = array();
    foreach ($words as $word) {
        $query = "SELECT Something";
        $result = $this->_db->fetchAll($query, "%".$word."%");
        foreach ($result as $row)
        {
            $id = $row['page_id'];
            if (!empty($final[$id][0]))
            {
                $final[$id][0] = $final[$id][0]+3;
            }
            else
            {
                $final[$id][0] = 3;
                $final[$id]['link'] = "/".$row['permalink'];
                $final[$id]['title'] = $row['title'];
            }
        } 
    }
.

코드가 잘 작동하는 것 같지만이 경고를 얻습니다.

Warning: Cannot use a scalar value as an array in line X, Y, Z (the line with: $final[$id][0] = 3, and the next 2).
.

누구 든지이 문제를 해결하는 방법을 말해 줄 수 있습니까?

도움이 되었습니까?

해결책

요소를 추가하기 전에 배열에 $final[$id]를 배열로 설정해야합니다.로 설정하십시오

$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
.

또는

$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
.

다른 팁

A bit late, but to anyone who is wondering why they are getting the "Warning: Cannot use a scalar value as an array" message;

the reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.

hope that helps

The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:

$data = [
"rs" => null
]

this above will work absolutely fine when used like:

$data["rs"] =  5;

But the below will throw a warning ::

$data = [
    "rs" => [
       "rs1" => null;
       ]
    ]
..

$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

Make sure that you don't declare it as a integer, float, string or boolean before. http://php.net/manual/en/function.is-scalar.php

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top