0

I'm having an array like this

$myArray = [
   [
       'key1' => $val1,
       'key2' => $val2,
       'key3' => $val3,
   ],
   [
       'key1' => $val4,
       'key2' => $val5,
       'key3' => $val6,
   ],
];

I want to convert $myArray into an assocciative array like this

$myArray = [
   $val3 => [
       'key1' => $val1,
       'key2' => $val2,
       'key3' => $val3,
   ],
   $val6 =>[
       'key1' => $val4,
       'key2' => $val5,
       'key3' => $val6,
   ],
];

Is there a php function or a combination of functions that does this for you?

1
  • What is $val3 and $val6 ? you mean the last key of each array? Commented Nov 9, 2020 at 9:14

4 Answers 4

1

One-liner, for better understanding in several lines:

print_r(
    array_combine(
        array_column($myArray, 'key3'),
        $myArray
    )
);
Sign up to request clarification or add additional context in comments.

Comments

1

maybe like this ?

function conv_arr($arr) {
    $newArr = [];
    foreach ($arr as $r) {
        $newArr[end($r)] = $r;
    }
    return $newArr;
}

Comments

1

If you want to get a new array with the last key of each array, try this:

<?php
$new = array();
$myArray = [
   [
       'key1' => 1,
       'key2' => 2,
       'key3' => 3,
   ],
   [
       'key1' => 4,
       'key2' => 5,
       'key3' => 6,
   ],
];

foreach( $myArray as $array ){
    end($array);
    $key = key($array);
    $new[$array[$key]] = $array;
}

print_r($new);

Using foreach only.

Comments

0

If your example output is illustrative of the pattern you intend to use, then you may use this example as a guide. See comments for a step-by-step explanation.

<?php

// Your variables defined.
$val1 = 1;
$val2 = 2;
$val3 = 3;
$val4 = 4;
$val5 = 5;
$val6 = 6;

// Your input array.
$myArray = [
   [
       'key1' => $val1,
       'key2' => $val2,
       'key3' => $val3,
   ],
   [
       'key1' => $val4,
       'key2' => $val5,
       'key3' => $val6,
   ],
];

$result = [];
// Loop over each element of your input array
foreach ($myArray as $el)
    // Use the value of the last element of each child array as the index to the child.
    $result[end($el)] = $el;

var_dump($result);

Output:

/*
array(2) {
  [3]=>
  array(3) {
    ["key1"]=>
    int(1)
    ["key2"]=>
    int(2)
    ["key3"]=>
    int(3)
  }
  [6]=>
  array(3) {
    ["key1"]=>
    int(4)
    ["key2"]=>
    int(5)
    ["key3"]=>
    int(6)
  }
}
*/

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.