Home > Blockchain >  How to merge array with custom value in laravel?
How to merge array with custom value in laravel?

Time:03-29

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

CodePudding user response:

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

CodePudding user response:

First of all, you are not combining here.YOu are just concating the two arrays. In Array combine, One will be the key and one will be the value at the output.The Following code will be the array combine in php :

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);

Output :

   Array(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

So here you can loop through the array and concate and finally push them into a new array.

$newArray = [];
foreach ($months as $key=>$month)
{
    foreach ($weeks as $keyWeek=>$week)
    {
        if($key == $keyWeek)
        {
            $value  = $month .'-'. $week;
           array_push($newArray,$value)
        }

    }
}

Or simply do this:

newArray = [];
foreach ($months as $key=>$month)
{
    $value  = $month .'-'. $weeks[$key];
    array_push($newArray,$value)
} 

CodePudding user response:

You can combine this array values using array_map function,

It can give high performance than foreach loop.

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

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

$newArray = array_map(function($index) use ($months, $weeks) {
    
    return $months[$index] . ' - ' . $weeks[$index];
    
}, array_keys($months));

echo '<pre>';
print_r($newArray);

Output:

Array
(
    [0] => January - Week 1
    [1] => January - Week 2
    [2] => January - Week 3
    [3] => January - Week 4
    [4] => February - Week 1
)

Demo: https://3v4l.org/ABJtf

  • Related