2

I have an array like this:

$arrayIn = [
     [ 0 => "3",
       1 => "12345"
     ],
     [ 0 => "2",
       1 => "123"
     ]
];

and want to get an array like this:

$arrayOut = [
     12345 => "3",
     123 => "2"   
];

I tried with array_values and array_combine but can't get this result. How can I do that?

0

2 Answers 2

5

You can use array_column for this

$arrayOut = array_column($arrayIn, 0, 1);

The second argument specifies which column to select and the third one specifies which column to use as keys.

Keep in mind that if you have duplicate values in column 1, they will be overwritten in the result because array keys must be unique by definition, but that caveat applies to any solution to this problem.

Sign up to request clarification or add additional context in comments.

Comments

1

You can just loop through your original array and build a new one with the second value as key and the first as value:

$arrayOut = [];
foreach ($arrayIn as $arr) {
    $arrayOut[$arr[1]] = $arr[0];
}
var_dump($arrayOut);

Demo

Result

array (size=2)
12345 => string '3' (length=1)
123 => string '2' (length=1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.