3

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?

1
  • this question is ambiguous, you should provide a bigger example set... Commented Mar 4, 2011 at 15:24

4 Answers 4

7

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.

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

3 Comments

how it is useful here can you expalin
$attributes = array_combine($myvar['aid'], $myvar['oid']);
This was it! Thanks so much! I still dont totally understand how its working, but I'll dig in deeper to see.
0

Somthing like this if I understood the question correct

$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
    $attributes[$v] = $myvar['oid'][$k]; 
}

1 Comment

Iteration like this is a waste of cycles and effort, and a bottleneck for very large array sets. The built-in array* functions are much more efficient.
0

Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties

1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid' 2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"

I think your are talking about 2nd option if so then use following code

$aAid = $myvar['aid'];
$aOid = $myvar['oid'];

foreach ($aAid as $key => $value) {
  $attributes['aid'][$key] = $value;
  $attributes['oid'][$key] = $myvar['oid'][$key];
}

Comments

-1

You can itterate though an array with foreach and get the key and values you want like so

$attributes = array() 
foreach($myvar as $key => $val) {
   $attributes[$key][0] = $val;
}

3 Comments

this is the same as $attributes = $myvar
Should be $attributes[$key] = $val[0]; for what the OP wants.
@blair your right i chanched my answer to reflect this change

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.