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条)

报告相同问题?