Tuesday, April 19, 2022

[FIXED] How to merge array with custom value in laravel?

Issue

I need help to concatenate 2 arrays with custom values, I've used tried array_merge() and array_combine(), the result is always not same with what I want please help me guys

Array 1

$month = [
'January',
'January',
'January',
'January',
'February'
];

Array 2

$weeks = [
'Week 1',
'Week 2',
'Week 3',
'Week 4',
'Week 1'
];

I want the output be like this

$newArray = [
'January - Week 1',
'January - Week 2',
'January - Week 3',
'January - Week 4',
'February - Week 1'
];

how to get the result like that


Solution

There isn't any function that will automatically give you the result you want. You need to iterate through the data and create it yourself:

$month = [
    'January',
    'January',
    'January',
    'January',
    'February'
];

$weeks = [
    'Week 1',
    'Week 2',
    'Week 3',
    'Week 4',
    'Week 1'
];

$newArray = [];

foreach ($month as $index => $value) {
    // Create the new string you want, using the same index for both arrays
    $newArray[] = $value . ' - ' . $weeks[$index];
}

Demo: https://3v4l.org/7qAoX



Answered By - M. Eriksson
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.