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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)