0

I have 2 arrays:

first[]:

Array
(
[First / Building] => code 100
[Second - Closed and Covered Cans] => code 200
)

second[]:

Array
(
[0] => 1,000.00
[1] => 2,000.00
[2] => 3,000.00
)

My desired out will be something like this :

final[]

Array
(
    [First / Building] => code 100
        (
            [0] => 1,000.00
        )

    [Second - Closed and Covered Cans] => code 200
        (
            [0] => 2,000.00
        )

)

(leave the [2] => 3,000.00 unmatched in this case)

If first[] count is > second[], let's say :

first[]

Array
(
[First / Building] => code 100
[Second - Closed and Covered Cans] => code 200
[Third - Closed and Covered Cans] => code 300
[Forth - Closed and Covered Cans] => code 400
)

second[]

Array
(
[0] => 1,000.00
[1] => 2,000.00
[2] => 3,000.00
)

My desired output :

final[]

Array
(
    [First / Building] => code 100
        (
            [0] => 1,000.00
        )

    [Second - Closed and Covered Cans] => code 200
        (
            [0] => 2,000.00
        )
     [Third - Closed and Covered Cans] => code 300
        (
            [0] => 3,000.00
        )
     [Forth - Closed and Covered Cans] => code 400
        (
        ) 
)

(leave the forth with no value in this case)

All the time pair the values from first array with the ones from second array. I tryed with array_combine(), but that isn't viable since they have different count.

3
  • 2
    Your desired result is not a valid array. An array element can't be both a string code 100 and also an array. Commented Jul 15, 2019 at 15:39
  • Maybe it should be something like "First / Building" => ['code' => 'code 100', 'price' => "1,000.00" ] Commented Jul 15, 2019 at 15:40
  • may be of use: stackoverflow.com/questions/19394980/… Commented Jul 15, 2019 at 15:41

1 Answer 1

0

array_combine is not useful because you don't have an array of keys. Your first array is already an associative array, and you want the result to have the same keys.

Use a foreach loop to go through the first array, while you increment a variable to get the index in the second array.

$final = [];
$i = 0;
foreach ($first as $key => $code) {
    $final[$key] = ["code" => $code, "price" => $second[$i]];
    $i++;
}
Sign up to request clarification or add additional context in comments.

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.