1

I have the following array:

Array ( [0] => Array ( [ContractorName] => Joe Soap [BonusAmount] => 73.92 ) [1] => Array ( [ContractorName] => Mike Michaels [BonusAmount] => 68.55 ) [2] => Array ( [ContractorName] => John Smith [BonusAmount] => 34.35 ) [3] => Array ( [ContractorName] => Pete Peterson [BonusAmount] => 24.61 ) [4] => Array ( [ContractorName] => Pete Smith [BonusAmount] => 22.76 ) ) 

How do I go about ending up with an array that looks like this:

Array ( [Joe Soap] => 73.92 [Mike Michaels] => 68.55 [John Smith] => 34.35 [Pete Peterson] => 24.61 [Pete Smith] => 22.76 ) 

I'm a bit lost at the moment. I have tried creating a new array by looping over the first array, but I'm getting unwanted results. Any help greatly appreciated.

0

3 Answers 3

4

Use array_combine with array_column as

array_combine(array_column($records, 'ContractorName'),array_column($records, 'BonusAmount')); 
Sign up to request clarification or add additional context in comments.

Comments

1

Go through entire array using foreach and then use each piece to construct new array.

$out = []; foreach ($inputArray as $v) { $out[$v['ContractorName']] = $v['BonusAmount']; } 

Second solution is by using array_combine and array_column.

$keys = array_column($inputArray, 'ContractorName'); $values = array_column($inputArray, 'BonusAmount'); $output = array_combine($keys, $values); //Or put everything in single line $output = array_combine(array_column($inputArray, 'ContractorName'), array_column($inputArray, 'BonusAmount')); 

Third option

$output = array_column($inputArray, 'BonusAmount', 'ContractorName'); 

1 Comment

Perfect. Works like a charm. Will give upvote and kudos in a few minutes. Thanks.
0

You can use one array_column(), and with the third parameter to specify the index. Live Demo.

array_column($array, 'BonusAmount', 'ContractorName'); 

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.