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

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>
  • 写回答

2条回答 默认 最新

  • 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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制