dongsicheng5262 2016-11-30 22:49
浏览 19
已采纳

PHP:数组值到字符串

So I’m trying to convert each value, of an array, into a string.. But I can’t get it to work. My best result is to get letters from the values.

I have a form where I post checkbox values into the database and later I want to echo the selected values:

<form method="POST">
<div class="form-group">
   <label class="form-check-inline">
      <input class="form-check-input" type="checkbox" name="genre[]" value="Rock"> Rock</label>

<label class="form-check-inline">
   <input class="form-check-input" type="checkbox" name="genre[]" value="Funk"> Funk</label>

<label class="form-check-inline">
   <input class="form-check-input" type="checkbox" name="genre[]" value=“Jazz”> Jazz</label>
</div>
</form>

if(isset($_POST['update_profile'])){
    $genre = implode(',', $_POST['genre']);
    $sql_update = "UPDATE user_profile SET genre = ‘$genre’ WHERE user_id = ‘$user_id’”;
…
}

In the database row the selected value look like this; “Rock, Funk, Jazz”

Fine. Everything seems to work as it should. But I can’t figure out how to separate the values..

        if($result = mysqli_query($con, $sql_all_users)){
          if(mysqli_num_rows($result) > 0){
            while ($row = mysqli_fetch_row($result)){
              $row_genre = array($row[1]);

        foreach ($row_genre as $key => $value) {
        echo $value[1];
        }

        }
    }
}

When I do a print_r ($row_genre); I get this result:

Array ( [0] => Rock,Funk,Jazz)

What kind of a array is that?

The result I echo in the foreach is R (The first letter in Rock - The first value ) I have tried to implode.. Dosen’t make a difference. So how can I convert each value to a string?

  • 写回答

2条回答 默认 最新

  • dqpciw9742 2016-11-30 23:04
    关注

    Looks like like $row[1] = Rock,Funk,Jazz so $row[1] itself is a string and comma-separated values.

    If you want to convert the string to an array you can do it using explode function:

    $row_genre = explode(',', $row[1]);
    

    You can then go through that $row_gen array like this:

    foreach($row_genre as $val) {
        echo $val;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错