0

I start with a MySQL query (not of my design) that returns results that look like:

 $row['user_name'];
 $row['user_property']
 $row['user_property_2']
 $row['day_1']
 $row['day_2']
 $row['day_3']
 $row['day_4']
 $row['day_5']

What I would like to do is quickly (ideally in one step, not in a loop) replace (re-key) all of the field names that contain 'day_' to just have the number, resulting in:

 $row['user_name'];
 $row['user_property']
 $row['user_property_2']
 $row['1']
 $row['2']
 $row['3']
 $row['4']
 $row['5']

but without any risk to the other field name keys.

I imagine some solution that involves an "swap" array like:

 $swap_array = ('day_1' => 1, 'day_2' => 2,'day_3' => 3, 'day_4' => 4, 'day_5' => 5);

But I'm not sure what function to implement the swap array. I am sure I've seen a native function for this before, but can't find it.

0

3 Answers 3

2
$arr = 
array_combine(
  explode(',', 
    preg_replace('/day_/', '', implode(',', array_keys($row)))), $row);

PS: what's wrong with loop?

potential problem 1 - if the return key like day_now might cause problem
potential problem 2 - if the return key contains comma, might cause problem

however, both potential problems can be fixed by enhance the regexp above


as for the native function, is array_map that you looking for?

Sign up to request clarification or add additional context in comments.

Comments

1

The only way I can think of it without looping is by using array_map:

$result = array_map(function($value, $key) use($swap_array) {
  return array(
    $value,
    isset($swap_array[$key]) ? $swap_array[$key] : $key
  );
}, $input_array);

Comments

1

The canonical method would be:

$key_map = array_replace(   # key => key               # XOR keys
    array_combine(array_keys($row), array_keys($row)), $swap_array
);
$row = array_combine(array_values($key_map), array_values($row));

However I would think that string replacement or any manual mapping would be faster and more readable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.