foreach中的数组到字符串转换

时间:2015-09-04 05:12:23

标签: arrays foreach

您好,

使用以下代码时,我得到一个字符串转换数组:

$sort_order = array();
foreach (getAll() as $field) {
        $sort_order[$field->name] = query("SELECT sort_order
                FROM field_table
                WHERE field_name = '$field->name'");                
      $o->tag[$field->name] = $field->title. $sort_order[$field->name];
            }

错误说第6行有一个数组到字符串的转换。为什么会这样?

谢谢。

2 个答案:

答案 0 :(得分:0)

query将返回一个数组,因此您需要执行以下操作:

 $result = query("SELECT sort_order
            FROM field_table
            WHERE field_name = '$field->name'");
$row = $result->fetch_assoc();
sort_order[$field->name] = $row['sort_order'];  

答案 1 :(得分:0)

是的,因为查询返回一个数组,该数组直接分配给变量。请试试这个:

  $sort_order = array();
  foreach (getAll() as $field) {
     $result = query("SELECT sort_order
        FROM field_table
        WHERE field_name = '$field->name'");

     while($res = $result->fetch_array()) {
        $sort_order = $res['sort_order'];
     }

     $o->tag[$field->name] = $field->title.$sort_order;
  }