Home > Software engineering >  I am looking for a way to change key name in a smart way
I am looking for a way to change key name in a smart way

Time:05-23

There are some arrays.

I would like them to assign week day name like below.

0=>sun   1=> mon   2=> tue  3=> wed   4=> thu  ... 6 => sat

e.g.1

array (
  0 => 'melon',
  1 => 'apple',
  2 => 'orange',
  3 => 'orange',
  4 => 'kiwi',
  5 => 'banana',
)  

//the result of e.g.1
array (
  "sun" => 'melon',
  "mon" => 'apple',
  "tue" => 'orange',
  "wed" => 'orange',
  "thu" => 'kiwi',
  "fri" => 'banana',
)  

e.g.2

array (
  0 => 'orange',
  1 => 'apple',
  2 => 'orange',
  3 => 'orange',
  4 => 'banana',
  5 => 'banana',
  6 => 'banana',
) 

e.g.3

array (
  5 => 'banana',
  6 => 'banana',
)  
//result e.g.3
array (
  "fri" => 'banana',
  "sat" => 'banana'
)  

e.g.4

array (
  3 => 'melon',
  6 => 'banana',
)  
//result e.g.4
array (
  "wed" => 'melon',
  "sat" => 'banana',
)  

Array size and key 0~6 is possibly changed.

I tried to use array_combine. but it is needed to match the size of keys.

$keys = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
$array = array_combine($keys, $values);

I wonder if there might be another way to do this.

CodePudding user response:

I dont think there is a magic bullet function for that so we will have to write something.

$fruitnVeg = [3 => 'melon', 6 => 'banana'];

$days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

function my_merge($days, $fruitnVeg)
{
    $ret = [];
    foreach( $fruitnVeg as $key => $val){
        $ret[$days[$key]] = $val;
    }
    return $ret;
}
$result = my_merge($days, $fruitnVeg);
print_r($result);

RESULT

Array
(
    [wed] => melon
    [sat] => banana
)

CodePudding user response:

There is no built-in way to combine uneven arrays as key/value, so you'll have to build something yourself.

This snippet will assign values to keys and stops once it has no keys left. All remaining values will be lost.

$keys = ['fruit', 'sweet', 'vegetable'];
$values = ['strawberry', 'chocolate', 'potato', 'juice'];
$i = 0;

foreach($keys as $key) {
  $keyedArray[$key] = $values[$i];
  $i  ;
}

This produces:

array(3) {
  ["fruit"]=>
  string(10) "strawberry"
  ["sweet"]=>
  string(9) "chocolate"
  ["vegetable"]=>
  string(6) "potato"
}

You could probably build something that looks more fancy using array_walk(), but why overcomplicate things?

  • Related