php 注意:php中数组到字符串的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19565118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
notice: array to string conversion in php
提问by HungryDB
<?php
$player[] = array();
$team_id = $_SESSION['tid'];
$team_pids = $con->prepare("SELECT p_id FROM players_to_team WHERE t_id = ?");
$team_pids->bindParam(1,$team_id);
$team_pids->execute();
while($info = $team_pids->fetch(PDO::FETCH_ASSOC))
{
$player[] = $info['p_id'];
echo $info['p_id'];
}
$pl_1 = $player[0];
.
.
.
$pl_10 = $player[9];
echo $player[0]; //notice here
echo $pl_1; //notice here
?>
<table>
$query = $con->prepare("SELECT role,name,value FROM players WHERE p_id = '".$pl_1."'");
// notice here
$query->execute();
while($result = $query->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>".$result['role']."</td>";
echo "<td>".$result['name']."</td>";
echo "<td>".$result['value']."</td>";
}
?>
</tr>
</table>
when i echo $info array it works fine, but when i echo $player array or $pl_1 variable or $result array values Notice appears...Array to string conversion and o/p doesn't show. why?
当我回显 $info 数组时它工作正常,但是当我回显 $player 数组或 $pl_1 变量或 $result 数组值时注意出现...数组到字符串转换和 o/p 不显示。为什么?
回答by Guillaume Chevalier
Try replacing $player[] = array();
by $player = array();
at the beginning (line 2).
尝试更换 $player[] = array();
通过 $player = array();
在开始时(第2行)。
This is because that you declare an array at the index 0 of this variable which is told to be an array because of the []
. You therefore try to place an array in your array, making it multidimensional.
这是因为您在此变量的索引 0 处声明了一个数组,由于[]
. 因此,您尝试在数组中放置一个数组,使其成为多维的。
回答by deceze
You cannot simply echo
an array. echo
can only output strings. echo 'foo'
is simple, it's outputting a string. What is echo
supposed to do exactly in the case of echo array('foo' => 'bar')
? In order for echo
to output anything here, PHP will convert array('foo' => 'bar')
to a string, which is always the string "Array"
. And because PHP knows this is probably not what you want, it notifies you about it.
你不能只是echo
一个数组。echo
只能输出字符串。echo 'foo'
很简单,就是输出一个字符串。什么是echo
应该在的情况下做的正是echo array('foo' => 'bar')
?为了在echo
此处输出任何内容,PHP 将转换array('foo' => 'bar')
为字符串,该字符串始终为 string "Array"
。因为 PHP 知道这可能不是您想要的,所以它会通知您。
The problem is you're trying to treat an array like a string. Fix that.
问题是您试图将数组视为字符串。解决这个问题。