4

I have a nested array with the information I need.

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 terribly useful. More useful would be

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

and so on.

Unfortunately my attempt

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

to date merely records the final value, without the associated key array(1) { [1]=> string(3) "360" }. Note: it doesn't matter if the key is stored as string or int!

2 Answers 2

2

This is already an array of hashmaps. So 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"]; 
}

Your can then use the key/value pair foreach method to check that this worked:

foreach($hashmap as $key => $value){
    echo 'map['.$key.']='.$value." \n<br/>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your array is two-dimensional. So the first dimension represents a key/value pair. Your solution is taking the key from the first dimension and not the second.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.