【问题标题】:Warning: Cannot use a scalar value as an array in警告:不能将标量值用作数组
【发布时间】:2014-02-26 18:05:25
【问题描述】:

我在执行状态脚本时看到以下错误:

Warning: Cannot use a scalar value as an array in 

$result[$array[$i*2]] = $array[$i*2+1];

我做错了什么? 我在下面包含了完整的代码:

<?php 

// Set the host and port 
$host = "ip_goes_here"; 
$port = port_goes_here; 

// Open the socket connection to the server 
$fp = fsockopen("udp://".$host, $port); 

// Set the string to send to the server 
$string = "\xff\xff\xff\xffgetinfo"; 

// Set the socket timeout to 2 seconds 
socket_set_timeout($fp, 2); 

// Actually send the string 
fwrite($fp, $string); 

// Read the first 18 bytes to get rid of the header and do the error checking here 
if(!fread($fp, 18)) { 

      die("Oh God, the pain!"); 
} 

// Get the status of the socket, to be used for the length left 
$status = socket_get_status($fp); 

// Read the rest 
$info = fread($fp, $status['unread_bytes']); 

// Explode the result of the fread into another variable 
$array = explode("\\", $info); 

// Loop through and create a result array, with the key being even, the result, odd 
for($i = 0; $i < count($array)/2; $i++) { 

    $result[$array[$i*2]] = $array[$i*2+1];
} 

// Print the result for error checking 
print_r($result);     

// Close the file pointer 
fclose($fp); 

我提到的那一行导致了错误。我不知道我在这里做错了什么......

【问题讨论】:

  • 显然$array 不是数组,即使变量如此命名。也可能是您已经将$result 设置为标量...如果不显示代码,您设置这些变量的位置,没有人可以告诉您出了什么问题。
  • 请提供完整代码 - 目前尚不清楚哪里出了问题
  • 对不起。我已经添加了整个代码。

标签: php arrays scalar


【解决方案1】:

您可以尝试在使用之前将变量$result 声明为数组。

$result = array();
// Loop through and create a result array, with the key being even, the result, odd 
for($i = 0; $i < count($array)/2; $i++) { 

    $result[$array[$i*2]] = $array[$i*2+1];
} 

【讨论】:

  • 这在 PHP 中不应该是必需的(但会生成一个 E_NOTICE 并且是不好的做法)
猜你喜欢
  • 1970-01-01
  • 2011-08-26
  • 2021-11-28
  • 2011-12-02
  • 1970-01-01
  • 2019-12-17
  • 2014-07-11
  • 2018-06-27
相关资源
最近更新 更多