문제

Assume that you have a PHP array like this, coming from a mysqli query:

$array = (
    'user_id' => 1
    'user_name' => 'User',
    'user_email' => 'mail@user.com'
);

Now I would like to create an instance of my user class. The constructor takes an array but the keys should be 'id', 'name', and 'email'.

What is the fastest way to edit the array above so that I get a new array like this:

$newArray = (
    'id' => 1
    'name' => 'User',
    'email' => 'mail@user.com'
);

$user = new User($newArray);

Of course I could simply loop through the original $array and use preg_replace() like this:

$newArray = array();

foreach ($array as $key => $value) {
    $newKey = preg_replace('/^user_/', '', $key);
    $newArray[$newKey] = $value;
}

But there surely is a faster way who could solve this problem? At the moment I cannot think of a good way, that's how I ended up here.

도움이 되었습니까?

해결책

If you're worried about performance, don't go doing trivial operations with regular expressions, they're inherently slow. Apart from that, since you're actively modifying keys, there's no other way than reconstructing a new array:

$params = [];
foreach($array as $key => $value)
  $params[substr($key, 5)] = $value;

In this code substr($key, 5) just strips the leading user_ part of each key and rebuilds the $params array to what you need. I'd be highly surprised if there was a faster solution.

If you actually want to check for data integrity and only extract the properly prefixed keys the problem becomes more complex:

function extractPrefixedElements(array $array, $prefix)
{
  $result = [];
  foreach($array as $key => $value)
  {
    list($pre, $newKey) = explode('_', $key, 2);
    if($pre == $prefix)
      $result[$newKey] = $value;
  }
  return $result;
}
extractPrefixedElements($array, 'user');

다른 팁

Surely you don't need preg_replace() here, because you're in the loop and regular expressions aren't always fast (because you initialize the whole engine on each iteration)

There's only one way you can do that - you should just replace user_ anywhere you encounter when iterating on array keys.

function prepare(array $array) {

   $result = array();

   foreach ($array as $key => $value) {
       $key = str_replace('user_', '', $key);

       $result[$key] = $value;
   }

   return $result;
}

// And finally
$newArray = prepare($array);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top