更改多维数组PHP的索引

时间:2018-09-05 07:45:36

标签: php arrays

我尝试了以下解决方案:

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

php array from multidimensional array keys values

但这并不是我所需要的,我试图混合一些解决方案,但没有提供帮助。

我的数据库中有一个数组:

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

我想将该数据库转换为:

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

该代码之后:

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

我的数组如下:

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

我尝试使用3x foreach,但是每次我以为我需要在我的foreach中更改一些变量,但都不知道怎么做时,都以错误结束。

3 个答案:

答案 0 :(得分:1)

现在,我看到其他答案了,看来您正在寻找array_column

它返回一个数组列,第三个参数是键名。

$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);

输出:

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

https://3v4l.org/ZAkgZ

无需循环即可解决此问题。

答案 1 :(得分:0)

您可以尝试以下操作:

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

此代码从数组的每个部分获取DATA作为键和VALUE作为值,并将其存储在$newArray中。

答案 2 :(得分:0)

假设$playerdata具有以下值

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);