drymoeuka282427675
2017-03-20 19:27
浏览 69
已采纳

如何将多维php数组转换为值为键的简单关联数组?

Language is PHP.

So I want to turn a multidimensional array into a simple associative array that uses every second value as a key and every third value as a value to that key.

The initial array looks like this:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Adam
        [value] => 150
    ),

[1] => Array
    (
        [id] => 2
        [name] => Bob
        [value] => 120
    ),

[2] => Array
    (
        [id] => 3
        [name] => Charlie
        [value] => 175
    )

)

I want to turn it into a simple associative array that looks like this:

Array
(
Adam => 150,
Bob => 120,
Charlie => 175
)

I tried (and failed with) something like this:

$initialArray;
$arrayPrepped = array();
    foreach ($initialArray as $part) {
        foreach ($part as $name => $value) {
            if ($name == 'name') {
                $key = $value;
            } elseif ($name == 'value') {
                $finalvalue = $value;
            }
            $finalpart = array($key => $finalvalue);
        }
        array_merge($initialArray, $finalpart);
    }

图片转代码服务由CSDN问答提供 功能建议

语言 PHP

所以我 想要将多维数组转换为一个简单的关联数组,该数组使用每秒的值作为键,每三个值作为该键的值。

初始数组如下所示:

  Array 
(
 [0] =>数组
(
 [id] => 1 
 [name] => Adam 
 [value  ] => 150 
),
 
 [1] =>数组
(
 [id] => 2 
 [名称] => Bob 
 [value] => 120  
),
 
 [2] =>数组
(
 [id] => 3 
 [名称] =>查理
 [值] => 175 
)
  
)
   
 
 

我想把它变成一个简单的关联数组,如下所示:

  Array  
(
 
Adam => 150,
Bob => 120,
Charlie => 175 
)
   
 
 

我尝试过(并失败了) 类似这样的事情:

  $ initialArray; 
 $ arrayPrepped = array(); 
 foreach($ initialArray as $ part){  
 foreach($ part as $ name =>  $ value){
 if($ name =='name'){
 $ key = $ value; 
} elseif($ name =='value'){
 $ finalvalue = $ value; 
}  
 $ finalpart = array($ key => $ finalvalue); 
} 
 array_merge($ initialArray,$ finalpart); 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • douluolan9101 2017-03-20 19:31
    最佳回答

    What about this one-liner!

    print_r(array_column($initialArray, 'value', 'name'));
    

    Read up on array_column.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题