duanjiancong4860 2014-08-06 12:01
浏览 44
已采纳

php数组在多个数组中选择一个键值并更改它们

is there a simple solution I can put inside a function to resolve the following:

I have multiple arrays as follows:

Array
(
[0] => A
[1] => 100_1
[2] => 1
[3] => 1184
[4] => 0
)

Array
(
[0] => A
[1] => 100_2
[2] => 2
[3] => 1185
[4] => 0
)

Array
(
[0] => A
[1] => 100_3
[2] => 3
[3] => 1186
[4] => 0
)

Array
(
[0] => A
[1] => 101_2
[2] => 2
[3] => 1188
[4] => 0
)

Array
(
[0] => A
[1] => 302
[2] => 0
[3] => 1161
[4] => 0
)

What I'd like to do is to select all the values which have _1,2,3 only, and remove the _1,2,3 so the desired result would be:

Array
(
[0] => A
[1] => 100
[2] => 1
[3] => 1184
[4] => 0
)

Array
(
[0] => A
[1] => 100
[2] => 2
[3] => 1185
[4] => 0
)

Array
(
[0] => A
[1] => 100
[2] => 3
[3] => 1186
[4] => 0
)

Array
(
[0] => A
[1] => 101
[2] => 2
[3] => 1188
[4] => 0
)

Array
(
[0] => A
[1] => 302
[2] => 0
[3] => 1161
[4] => 0
)

Notice only values which contain _1,2,3 have been changed. Many thanks for your help it's much appreciated.

The code I have so far is:

foreach($data as $line) {
    if(substr($line,0,1)=="A") {
    if(!$first) {
        $parts = explode(chr(9), $line);            
        list($num1, $num2) = explode('_', $parts[1]); //this code needs to come first
        $parts[2] = isset($num2) ? $num2 : $parts[2]; //it replaces key[2] with _* (1,2,3)

//echo "<pre>"; print_r($parts); echo "</pre>";

   //the code to remove _* needs to go here.

    $pos = strpos($parts[1], '_');  // this was all it needed a simple two liner
    if($pos !== false) $parts[1] = substr($parts[1], 0, $pos);
  • 写回答

5条回答 默认 最新

  • douluoxiao2286 2014-08-06 12:09
    关注

    Assuming the _1 etc. always happens in array[1]

    foreach($array as $row) {
        $pos = strpos($row[1], '_');
        if($pos !== false) $row[1] = substr($row[1], 0, $pos);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?