简体   繁体   中英

How to access the changing key in an associative multidimensional array

I have this array:

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"
  ]
]

I have to count the count values ​​for each key. But the names of keys have different names. And I do not know how to get access to them. I want to get such result:

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

I tried to use two foreach loops

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

But the result is incorrect

You could try something like this :

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

Outputs :

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

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

)

I assumed user x and key x were just placeholders for any values.

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

edit: comments added

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