drddx3115
drddx3115
2015-04-21 04:21
浏览 134
已采纳

php获取数组中特定索引的值

I have this problem. I want to echo the value of the specific index of an array. my code is this.

<?php
$str = 'test1:val1,test2:val2,test3:val3'
$ex1 = explode(',',$str);
foreach($ex1 as $val){
  $ex2 = explode(':',$val);
  foreach($ex2 as $val2){
    echo $val2.'<br>';
  }
}

//the output will be
/*
test1
val1
test2
val2
test3
val3
*/
?>

But I want the output to be only test1,test2,test3. Plss someone help me.

</div>

图片转代码服务由CSDN问答提供 功能建议

我有这个问题。 我想回显一个数组的特定索引的值。 我的代码就是这个。

 &lt;?php 
 
 $ str ='test1:val1,test2:val2,test3:val3'  
 
 $ ex1 = explode(',',$ str); 
 
foreach($ ex1 as $ val){
 
 $ ex2 = explode(':',$ val); 
 
  foreach($ ex2 as $ val2){
 
 echo $ val2。'&lt; br&gt;'; 
 
} 
 
} 
 
 
 
 //输出将是
 
  \ N / * 
 
test1 
 
val1 
 
test2 
 
val2 
 
test3 
 
val3 
 \ N * / 
 
&GT;   \  r 
  
 
  
 
 
 
 

但我希望输出只是test1,test2,test3。 Plss有人帮助我。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglu4159
    donglu4159 2015-04-21 04:27
    已采纳

    Just get the substring with substr & strpos. Try with -

    $str = 'test1:val1,test2:val2,test3:val3';
    $ex1 = explode(',',$str);
    
    foreach($ex1 as $val){
      $test = substr($val, 0, strpos($val, ':'));
      echo $test."<br>";
    }
    

    Or you can do this also -

    $str = 'test1:val1,test2:val2,test3:val3';
    $ex1 = explode(',',$str);
    foreach($ex1 as $val){
      $ex2 = explode(':',$val);
      echo $ex2[0]."<br>";
    }
    
    点赞 评论
  • dongtang1918
    dongtang1918 2015-04-21 04:51

    You've already accepted an answer, but you can skip a couple lines and do a preg_match_all():

    $str = 'test1:val1,test2:val2,test3:val3';
    preg_match_all('/([^\,\:]{1,})\:([^\,\:]{1,})/',$str,$match);
    echo implode(",<br />",$match[1]);
    
    点赞 评论

相关推荐