0

I have two PHP arrays, and would like to append the value of the first array to the second array to create a new array which reiterates the original order but combines both values. I have tried the PHP array_merge but this just appends the new array but not merge into single values.

Array
(
    [0] => Array
        (
            [title] => Item 1
        )
    [1] => Array
        (
            [title] => Item 2
        )
    [2] => Array
        (
            [title] => Item 3
        )
    [3] => Array
        (
            [title] => Item 4
        )
)

Second array;

Array
(
    [0] => Array
        (
            [count] => 3
        )
    [1] => Array
        (
            [count] => 6
        )
    [2] => Array
        (
            [count] => 9
        )
    [3] => Array
        (
            [count] => 2
        )
)

Completed array;

Array
(
    [0] => Array
        (
            [title_count] => Item 1 (3)
        )
    [1] => Array
        (
            [title_count] => Item 2 (6)
        )
    [2] => Array
        (
            [title_count] => Item 3 (9)
        )
    [3] => Array
        (
            [title_count] => Item 4 (2)
        )
)
1
  • I don't think there's anything built-in that will do this. You'll have to write a loop that does it. I've never before seen the need to concatenate array keys like that. Commented Sep 21, 2016 at 23:00

1 Answer 1

1

Just use a foreach loop.

$result = array();
foreach ($array1 as $i => $element) {
    $title = $element['title'];
    $count = $array2[$i]['count'];
    $result[] = array('title_count' => "$title ($count)");
}
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.