douliang2935 2018-05-25 07:37
浏览 768
已采纳

将数组转换为字符串或对象

Good day, I am trying to convert an array "$list" into string or object. I have used following methods:

<?php

include "medclass.php";

session_start();
if (isset($_SESSION['mail'])) 
{
    $list = $_SESSION['basket'];
}
else
header("location: clientsigninpage.php?msg= Log-in First");

$obj = new med_class;
$obj->connectdb();

$val = implode(";",$list);    //implode method
$val = (object) $list;        //object method
$val = serialize($list);      //serialize method

$result = $obj->searchMed($val);

while ($row = $result->fetchObject()) 
{
  echo $row->MedPrice;
}

?>

With "(object)" its giving me following error: "Object of class stdClass could not be converted to string", with "implode": "Array to string conversion" and with "serialize()" it does not print anything.

The function that I am passing value is:

function searchMed($v1)
    {
        $sql = "select * from storepreview where MedName = '$v1'";
        $ret = $this->con->query($sql);
        return $ret;
    }

I have used these methods by seen following links: (http://www.dyn-web.com/php/arrays/convert.php) ; (Convert an array to a string); (How to convert an array to object in PHP?)

  • 写回答

2条回答 默认 最新

  • drpkcwwav20524605 2018-05-25 16:09
    关注

    I managed to reproduce your "Array to string conversion" error when using the implode command by running the following line of code:

    implode(";", [[]]); // PHP Notice:  Array to string conversion in php shell code on line 1
    

    For converting a nested array into a string I found that a foreach loop worked:

    $nestedArray = ['outerKeyOne' => ['innerKeyOne' => 'valueOne'], 'outerKeyTwo' => ['innerKeyTwo' => 'valueTwo']];
    $arrayOfStrings = [];
    foreach ($nestedArray as $key => $value) {
        $arrayOfStrings[] = implode(",", $value);
    }
    implode(";", $arrayOfStrings); // string(17) "valueOne;valueTwo"
    

    The second error associated with the line $val = (object) $list; is from trying to embed an object into the $sql string. It seems like an object is not what you want here, unless it is an object that has a __toString() method implemented.

    I hope this is of some help. Using var_dump or something similar would provide more debug output to better diagnose the problems along with the above error messages. That's how I came up with the above code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发