简体   繁体   中英

Change index of multidimensional array PHP

I've tried some solutions from:

In PHP, how do you change the key of an array element?

php array from multidimensional array keys values

But its is not exacly what i need, i tried to mix some solutions but notting helped.

I have an array from my database:

Array ( 
    [0] => Array (
        [ID] => 1 
        [USER_ID] => 1
        [DATA] => UNIQUE 
        [VALUE] => buuu ) 
    [1] => Array (
        [ID] => 2 
        [USER_ID] => 1 
        [DATA] => NICKNAME 
        [VALUE] => NoAd ) ) 

And i want to transform that database to:

Array ( 
    [UNIQUE] => buuu
    [NICKNAME] => NoAd
    [any new [2]...[3]... from previous array

after that code:

foreach($playerdata as $segment){
                    foreach($segment as $key => $value ){
                    $newArray[$value] = $value;
                }
            }

my array looks like:

Array ( [UNIQUE] => UNIQUE 
        [buuu] => buuu 
        [NICKNAME] => NICKNAME 
        [NoAd] => NoAd ) 

i tried use 3x foreach but it ends in error all time i think i need to change some variables in my foreach but no idea how.

Now that I see the other answers it seems it's array_column you are looking for.

It returns an array column and the third parameter is what the key name should be.

$player_data = array(array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "UNIQUE",
"VALUE" => "buuu"
),
array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "NICKNAME",
"VALUE" => "NoAd"
));
$new = array_column($player_data, "VALUE", "DATA");
var_dump($new);

Output:

array(2) {
  ["UNIQUE"]=>
  string(4) "buuu"
  ["NICKNAME"]=>
  string(4) "NoAd"
}

https://3v4l.org/ZAkgZ

There is no need for loops to solve this.

You could try something like the following:

$newArray = array();    
foreach($playerdata as $segment){
    $newArray[$segment['DATA']] = $segment['VALUE'];
}

This code gets the DATA as key and VALUE as value from each part of the array and stores it in $newArray .

lets assume $playerdata has the below values

Array ( 
    [0] => Array (
        [ID] => 1 
        [USER_ID] => 1
        [DATA] => UNIQUE 
        [VALUE] => buuu ) 
    [1] => Array (
        [ID] => 2 
        [USER_ID] => 1 
        [DATA] => NICKNAME 
        [VALUE] => NoAd ) ) 
    [2]----
    [3]----        

$newArray = [];
foreach($playerdata as $record) {
    $newArray[$record['DATA']] = $record['DATA'];
    $newArray[$record['VALUE']] = $record['VALUE'];
}

print_r($newArray);

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