【问题标题】:Convert String to an array with PHP使用 PHP 将字符串转换为数组
【发布时间】:2021-10-23 06:59:50
【问题描述】:

我用添加字符串和变量的变量创建了一个数组,我想将此字符串添加到另一个数组,问题是当我使用 javascript 控制台记录它时,它显示为字符串而不是数组,这也使我无法访问数组数据。这是我的代码:

    foreach($datas as $data) {
        $currentusername = $data['username'];
        $currentpassword = $data['password'];
        $currentage = $data['age'];
        $objectresult = "['Username' => ${currentusername}, 'Password' => ${currentpassword}, 'Age' => ${currentage}]";
        
        print $objectresult."<br/>";
        array_push($usuarios, $objectresult);
    }
    ?>

    <script language="JavaScript">
        var num = <?php echo json_encode($usuarios) ?>;
        for(let i = 0; i < num.length; i++) {
            console.log(num[i]);
        }
    </script>

【问题讨论】:

  • 您将 $objectresult 构建为字符串 - 是否有任何理由不将其创建为数组?
  • PHP 的 json_encode() 将数组转换为字符串。听起来您想使用 Javascript 的 JSON.parse() 函数,例如var num = JSON.parse(&lt;?php echo json_encode($usuarios) ?&gt;).

标签: php arrays string object


【解决方案1】:

数组不要用引号引起来,应该是普通的PHP数组。

$objectresult = ['Username' => $currentusername, 'Password' => $currentpassword, 'Age' => $currentage];

【讨论】:

    猜你喜欢
    • 2014-07-15
    • 1970-01-01
    • 2018-01-29
    • 2013-08-12
    • 2021-12-27
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多