Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PHP array into Key => Value Array

Tags:

arrays

php

Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!

$myvar is an array that looks like this:

Array (  
 [aid] => Array (  
  [0] => 2  
  [1] => 1  
 )  
 [oid] => Array(  
  [0] => 2  
  [1] => 1  
 )  
)

And I need to set a new variable (called $attributes) to something that looks like this:

$attributes = array(
 $myvar['aid'][0] => $myvar['oid'][0], 
 $myvar['aid'][1] => $myvar['oid'][1], 
 etc...
);

And, of course, $myvar may contain many more items...

How do I iterate through $myvar and build the $attributes variable?

like image 479
Feature Avatar asked Mar 22 '26 17:03

Feature


1 Answers

use array_combine()

This will give expected result.

http://php.net/manual/en/function.array-combine.php

Usage:

$attributes = array_combine($myArray['aid'], $myArray['oid']);

Will yield the results as requested.

like image 119
Gaurav Avatar answered Mar 25 '26 06:03

Gaurav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!