duanjia2772 2014-12-02 08:32
浏览 81
已采纳

我如何将逗号分隔列表转换为方括号数组

I have this variable $csv = '3,6,7,8'; that i need to convert to a square bracketed array of the form $csv_array = [3,6,7,8];

If i explode the csv like $new_array=explode(",",$csv);,it does not give me the array i want.

This is a running example http://3v4l.org/kYC0g

The code

$csv = '3,6,7,8';
$new_csv = '['.$csv.']';

if(is_array($new_csv)){
echo 'true';
}
else{
echo 'false';
//this is false
}

echo '<br/>';
$new_array=explode(",",$csv);

print_r($new_array);
//not what i am looking for

echo '<br/>';

print_r($new_csv);

echo '<br/>';

echo $new_csv;
  • 写回答

2条回答 默认 最新

  • douhoujun9304 2014-12-02 08:34
    关注

    As stated by a fellow stacker

    RichardBernards - The two 'types' of array are exactly the same in PHP. If you are looking for JSON

    An example of using JSON to achieve what it is you require:

    To encode:

    $csv = '3,6,7,8';
    $array = explode(",", $csv);
    $json = json_encode($array);
    
    echo $json;
    

    To decode $csv into the normal array you provided it:

    $decoded = json_decode($json, true);
    var_dump($decoded);
    

    And then to return it to its original format:

    $csv = implode(',', $decoded);
    

    See json_encode() for more information, and also see it's opposite json_decode()

    Keep in mind that JSON is literally a string and is not compatible associatively in PHP until it is decoded using the json_decode() function mentioned above. With that being said, replacing true with false in the example above would create an object array and multi-dimensional arrays would require them to be referenced differently, e.g. $array->result.

    It would also be worth bringing to your attention the beauty of the predefined CSV functions within PHP

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

报告相同问题?

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器