2

I am fairly new to PHP and working my way through it. I've managed to solve most problems independently, but this one has had me scuppered for a while. Any help is much appreciated!

I have a series of arrays produced by a form, as follows:

description_array = description1, description2, description3
account_array = account1, account2, account 3

Where I am trying to get to is:

item_array = 1 => description1, account1, 2 => description2, account2

It may be that I am struggling with the logic more than the actual code. I've tried all sorts of manipulations with foreach and while loops with little success.

Any thoughts gratefully received.

Thanks Aaron

4 Answers 4

3

If the arrays are guaranteed to be balanced in size the you could do this.

$res = array();
for($x=0; $x<count($description_array); $x++){
       $res[] = array($description_array[$x], $account_array[$x]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

$description_array[$i], $account_array[$i]...$i should be $x, but other than that correct
Thank you - this works a treat (with the edit Jonathan provided)!
1

You could use the key from 1 array to get the value of another array:

$description_array = array('description1', 'description2', 'description3');
$account_array = array('account1', 'account2', 'account3');

$item_array = array();
foreach($description_array as $key=>$val){
    $item_array[] = array($val,$account_array[$key]);
}

echo '<pre>',print_r($item_array),'</pre>';

Comments

0

Derp. I totally misread. And in the time it took me to fix it other people answered, but oh well. Here it is :)

$items = array();
foreach($description AS $k=>$v){
    if(isset($account[$k])){ 
        $items[$k] = array($v, $account[$k]); // assuming you don't really want a comma sep string, but another array.
    }
}

Comments

0

If they are both equally large, it's probably simplest to iterate over one of the arrays and fill in the new array.

$item_array = array();
foreach ($description_array as $key => $description) {
    $item_array[$key] = array(
        'description' => $description,
        'account' => $account_array[$key]
    );
}

That's also easy to extend if you add further arrays.

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.