如何在PHP中拆分逗号值

时间:2016-11-16 08:54:46

标签: php

我在$ _POST中有一个数组:

Array ( [tags] => 1,2,3,4,5) 

如何将此数组转换为数组,如下所示:

Array ( [tag1] => 1 [tag2] => 2 [tag3] => 3 [tag4] => 4 [tag5] => 5)

5 个答案:

答案 0 :(得分:2)

$ tags = explode(",",$ _POST [' tags']); 的print_r($标签);

$sqlUserLevel = $user_home->runQuery("SELECT * FROM po_users");
$sqlUserLevel->execute();
$loggedInUserRole = $sqlUserLevel->fetch(PDO::FETCH_ASSOC);

答案 1 :(得分:1)

使用foreachexplode -

$newArr = array();
foreach (explode(', ', $_POST[tags]) as $val) {
  //modify the key with prepending the tag string
  $key = "tag{$val}";
  $newArr[$key] = $val;
}

print_r($newArr); //this will be your required array

答案 2 :(得分:0)

<?php
$array = array( 'tags' => ['1','2','3','4','5']);

foreach( $array as $key => $value )
{
  foreach( $value as $t )
  {
     $new[ 'tag'.$t ] = $t;
  }
}
var_dump( $new );

根据需要保留数组键。

答案 3 :(得分:0)

请使用explode函数将字符串转换为数组。

$tagsStr=$_POST['tags'];

 $tagArray=explode(",",$tagsStr);

答案 4 :(得分:-1)

尝试以下代码: 假设$ _POST [&#39;标签&#39;]存在

//the $arr will have key beginning from 0 to the upper bound number
$arr=explode(",",$_POST['tags']);

//to get tags1, tags2 etc. as key try the following
$cnt=1;
$newArray=array();
foreach($arr as $a){
    $newArray['tags'.$cnt]=$a;
    $cnt++;
}
print_r($newArray);