Home > Software design >  Problem with a specific task using associative arrays in PHP
Problem with a specific task using associative arrays in PHP

Time:10-29

I've been stuck on this for the better part of the day and I'm out of ideas. I have an array like this:

    Array
(
    [rank] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [name] => Array
        (
            [0] => 'Hideki'
            [1] => 'Rory'
            [2] => 'Sam'
    [money] => Array
        (
            [0] => '$100'
            [1] => '$200'
            [2] => '$500'          
        )
)

and I have the task to create an array with the following format from it:

       Array
    (
    [Hideki] => Array
        (
            [rank] => 1
            [money] => '$100'
        )
    [Rory] => Array
        (
            [rank] => 2
            [money] => '$200'
    [Sam] => Array
        (
            [rank] => 3
            [money] => '$500' 
        )
)

The catch is that 'rank' and 'money' have to be dynamic names

CodePudding user response:

It should be simple as that:

$new = [];

foreach($array['name'] as $key => $name) {
    $new[$name] = [
        'rank' => $array['rank'][$key],
        'money' => $array['money'][$key]
    ];
}

CodePudding user response:

Run your first array through a foreach loop referencing only the "name" key and using key=>value pairs. Then reference the other keys from the first array when you build the new array, setting the value as the key to the second array.

Example:

foreach($array1['name'] as $key=>$value){
   $array2[$value] = array(
       'rank'=>$array1['rank'][$key],
       'money'=>$array1['money'][$key]
   );
}

CodePudding user response:

Little late but here my answear. My approach was to use the array_walk() function.

$array = [
    'rank' => [1,2,3],
    'name' => ['Hideki', 'Rory', 'Sam'],
    'money' => ['$100', '$200', '$500'],
];

$i = 0;
$newArray = [];
array_walk($array['name'], function($name) use (&$i, $array, &$newArray) {
    $newArray[$name] = ['rank'=> $array['rank'][$i], 'money' => $array['money'][$i]];
    $i  ;

});
print_r($newArray);

CodePudding user response:

I see you that say that "rank" and "money" can be named dynamically. The other answers are close in that case but you can try this maybe:

(This is assuming that the array is always formatted the same, eg. "rank" is always position 0 and "money is always position 2", then it doesn't matter what they are named)

Seems messy to me though, are you creating this initial array?

Anyways, adapted from Robert's answer:

$new = [];
$keys = array_keys($array);

foreach($array['name'] as $key => $name) {
    $new[$name] = array(
        'rank' => $array[$keys[0]][$key],
        'money' => $array[$keys[2]][$key]
    );
}
  • Related