0

So lets say, i have First Array with values like this

First Array :

$first : [Array
(
    [0] => CreationDate
    [1] => OrderNumber
    [2] => OrderDate
    [3] => InvoiceNumber
)

and Second Array with value like this : $Second : [Array

(
    [0] => 2011-08-09
    [1] => 123123
    [2] => 2011-08-09
    [3] => XXAXXA
)

what i want is to get output like this :

$Join : [Array
(
    [CreationDate] => 2011-08-09
    [OrderNumber] => 123123
    [OrderDate] => 2011-08-09
    [InvoiceNumber] => XXAXXA

)

*noted, i already using this nested foreach to get the result

$join = array();

    foreach ($names as $key => $value) {
    foreach ($values as $key2) {      
        $join[][$value] = $key2;
    }

}

but it return Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 29364224 bytes)

so if u guys have more efficient method, i open my mind to know it Thanks u guys

2 Answers 2

1

You could use array_combine and use the first array for the keys and the second array for the values:

$a = [
    0 => "CreationDate",
    1 => "OrderNumber",
    2 => "OrderDate",
    3 => "InvoiceNumber"
];
$b = [
    0 => "2011-08-09",
    1 => "123123",
    2 => "2011-08-09",
    3 => "XXAXXA"

];

print_r(array_combine($a, $b));

Output:

Array
(
    [CreationDate] => 2011-08-09
    [OrderNumber] => 123123
    [OrderDate] => 2011-08-09
    [InvoiceNumber] => XXAXXA
)

Demo

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

3 Comments

yess, it worked, but i have 672 lines in $First and $Second Array, both of them is 672 lines, when i use combine it stuck, it only combine 22 lines, any suggesttion ?
So after 22 lines you get the Fatal error? Dit you try to increase the memory a bit? Perhaps there is some very inefficient looping?
@hope9 We can only work with the details you give in your question. If your actual array is different, you need to update the question with this details. Are all 672 items in the first array unique?
0
$join = array();

foreach ($names as $key => $value) {
    $join[$value] = $values[$key];
}

which $names and $values are your arrays.

Edit:

Since you run out of memory, I would recommend you to unset the original array.

$join = array();

foreach ($First as $key => $value) {
    $join[$value] = $Second[$key];
    unset($First[$key]);
    unset($Second[$key]);
}

and use array_keys($join) to get the first array and array_values($join) to get the second array.

1 Comment

it work, but only few lines, actually i got 672 line in $First array and $Second array

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.