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条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)