How to create a hash table from a nested array (php)

I have a nested array with the necessary information.

array(66) {
  [0]=>
  array(2) {
    ["key"]=>
    string(1) "9"
    ["value"]=>
    string(1) "9"
  }
  [1]=>
  array(2) {
    ["key"]=>
    string(3) "104"
    ["value"]=>
    string(1) "3"
  }
  [2]=>
  array(2) {
    ["key"]=>
    string(3) "105"
    ["value"]=>
    string(1) "1"
  }
...

However, this format is not very useful. It would be more useful

[9]=>9
[104]=>3
[105]=>1

etc.

Sorry, my attempt

foreach ($arrayname as $key => $value) {
             $i= ((int) $value);
             $hashmap[$i] = ($value["value"]); 
            }

today it simply writes the final value without the corresponding key array (1) {[1] => string (3) "360"}. Note: it does not matter if the key is saved as a string or int!

+4
source share
2 answers

This is already an array of hashmaps. Therefore, you should use it that way. You are not interested in the keys 0, 1, ..here, I suppose.

$hashmap = array();
foreach ($arr as $value) {
    $hashmap[$value["key"]] = $value["value"]; 
}

Then you can use the key / value foreach method to verify that this worked:

foreach($hashmap as $key => $value){
    echo 'map['.$key.']='.$value." \n<br/>";
}
+2

. , /. , .

$hashmap = [];
foreach($arrayname as $pair) {
    $key           = $pair['key'];
    $value         = $pair['value'];
    $hashamp[$key] = $value;
}
+1

Source: https://habr.com/ru/post/1621182/


All Articles