简体   繁体   中英

PHP extracting values from array and restoring them into another array

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM