如何访问关联多维数组中的更改键

时间:2018-03-08 22:24:58

标签: php

我有这个数组:

array: [
  0 => array: [
    "key 1" => "user 1",
    "count" => "14"
  ],
  1 => array: [
    "key 2" => "user 2",
    "count" => "7"
  ],
  2 => array: [
    "key 2" => "user 1",
    "count" => "1"
  ]
]

我必须计算每个键的计数值。但是键的名称有不同的名称。我不知道如何访问它们。 我想得到这样的结果:

array: [
  0 => array: [
    "user" => "user 1",
    "key 1" => "14",
    "key 2" => "1",
  ],
  1 => array: [
    "user" => "user 2",
    "key 2" => "7"
  ]

我尝试使用两个foreach循环

foreach ($result as $k=>$v)
            {
                foreach ($v as $k2=>$v2) {
                    $final[]["user"] = $result[$k][$k2];
                }
            }

但结果不正确

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

$result = [
  ["key 1" => "user 1", "count" => "14"],
  ["key 2" => "user 2", "count" => "7"],
  ["key 2" => "user 1", "count" => "1"]
];


$out = [] ; // output array 
foreach ($result as $val) {
    $keys = array_keys($val); // get the keys "key 1", "count" as array
    $uid = reset($val); // get the first value "user 1"
    $out[$uid]['user'] = reset($val); // store the user name
    $out[$uid][reset($keys)] = $val['count']; // store the count into "key N" key. 
}
$out = array_values($out); // reindex keys 
print_r($out); // output data (optional)

输出:

Array
(
    [0] => Array
        (
            [user] => user 1
            [key 1] => 14
            [key 2] => 1
        )

    [1] => Array
        (
            [user] => user 2
            [key 2] => 7
        )

)

答案 1 :(得分:0)

我认为user xkey x只是任何值的占位符。

$b = array();
foreach ($a as $row)
{
    $values = array_values($row);
    $keys = array_keys($row);

    //Extract data from keys / values
    $user = $values[0];
    $key = $keys[0];
    $count = $values[1];

    //Create element in output array and insert user info
    if ( ! isset($b[$user]))
    {
        $b[$user] = array('user' => $user);
    }

    //Add key info
    $b[$user][$key] = $count;
}
//Rewrite array keys to 0, 1, 2, ...
$b = array_values($b);

编辑评论已添加