1

I have 3 arrays like so, that can contain an infinite number of items:

Weight Array ( [0] => 20 [1] => 250 [2] => 400 )
Price Array ( [0] => 1.20 [1] => 6.00 [2] => 9.50 )
Courier Array ( [0] => DHL [1] => DHL [2] => UPS )

I'd like to merge them and sort them like so:

    Array (
        [0] => 20
        [1] => 1.20
        [2] => DHL
        [3] => 250
        [4] => 6.00
        [5] => DHL
        [6] => 400
        [7] => 9.50
        [8] => UPS
    ) 

Is there a built in PHP function that does this or will I have to write my own?

3 Answers 3

5

There is no need in function, I suppose:

for ($i=0; $i<count($WeightArray); $i++) {
  $TargetArray[] = $WeightArray[$i];
  $TargetArray[] = $PriceArray[$i];
  $TargetArray[] = $CourierArray[$i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Upvoting this answer, as the others recommend array_merge which does not work as requested by the original question.
0

There is indeed one built-in.

https://www.php.net/array_merge

2 Comments

array_merge just appends each array to the end of the previous one, I want to sort them too.
ah sorry. read too fast. you don't really want to sort them, you just want to use element 0 from array 0, element 0 from array 1, element 0 from array, element 0 from array 1... So to me it looks like you want to keep track of the corresponding weights, prices, and couriers. Why not use objects?
0
$newarray = array_merge($array1,$array2);

This should do the trick, you can add as many parameters as you want to add more 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.