douju1997 2013-12-31 18:46
浏览 44
已采纳

PHP从数组中提取值并将它们还原到另一个数组中

I have an Array of values pulled from a mysql table of the form:

$name_ids = EMP-646
            EMP-545
            EMP-12
            CLIENT-36
            CLIENT-43
            CLIENT-5

I would like to identify EMP and CLIENT as separate data and then extract only the integer values and then store them into separate variables. For example:

$emp_id =    646
             545
             12

$client_id = 36
             43 
             5

Here is my attempt at it but I am unable to print the desired results (not sure if my logic is correct):

$name_ids = array($_SESSION['INVITED_NAMES']);

foreach($name_ids[0] as $name_id){
  if(stripos($name_id, 'EMP') !== false){ 
    $emp_id = preg_replace("/[^0-9]/","",$name_id);
  }
  elseif(stripos($name_id, 'CLIENT') !== false){ 
    $client_id = preg_replace("/[^0-9]/","",$name_id);
  }

  echo $emp_id.' '; //both results need to happen at this stage in the `foreach` loop.
  echo $client_id.' ';              
}

One thing to note is I need the results to appear where they are due to other code that is dependent on this location. With the present code this is the results I get:

646 545 12 36 12 43 12 5 12

The error appears at the first if statement($emp_id), when a value is false it returns the last int of a true value until the loop is through. Any help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dongyong3554 2013-12-31 19:01
    关注

    Here it is working: https://eval.in/84445

    Relevant code:

    $emp_ids = array();
    $client_ids = array();
    
    $name_ids = array('EMP-646',
                'EMP-545',
                'EMP-12',
                'CLIENT-36',
                'CLIENT-43',
                'CLIENT-5');
    
    var_dump($name_ids);            
    
    foreach($name_ids as $name_id){
      if(stripos($name_id, 'EMP') !== false){ 
        $emp_id = preg_replace("/[^0-9]/","",$name_id);
        array_push($emp_ids, $emp_id);
      }
      elseif(stripos($name_id, 'CLIENT') !== false){ 
        $client_id = preg_replace("/[^0-9]/","",$name_id);
        array_push($client_ids, $client_id);
      }
    
    }
    
    echo "Emp_ids are: ";
    var_dump($emp_ids);
    
    echo "Client_ids are: ";
    var_dump($client_ids);
    

    I just created arrays to store the values, and pushed them in.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?