Rohan Krishna
Rohan Krishna

Reputation: 417

How to merge multiple arrays in PHP and output the values together?

I have a situation while developing an application on Laravel. I have three arrays in the following order. I need to merge them and display their values in the following order too. Here , it goes.

stone_name['ruby','diamond','catseye'];
stone_weight[112,223,445];
stone_rate[1000,2500,670];

I need to merge these three arrays and display the out put in this order.

stone_info = array(stone_name[0] , stone_weight[0] , stone_rate[0]);

So that the final result will be like :

stone_info = array("ruby",112,1000);

Upvotes: 0

Views: 101

Answers (1)

Saiyan Prince
Saiyan Prince

Reputation: 4020

I was in the same situation and I had done it in this way. May be this can help you out.

<?php

$stone_name = ['ruby','diamond','catseye'];
$stone_weight = [112,223,445];
$stone_rate = [1000,2500,670];

$result = mergeArrays($stone_name, $stone_weight, $stone_rate);

function mergeArrays($stone_name, $stone_weight, $stone_rate) {
    $result = array();

    foreach ($stone_name as $key => $name ) {
        $result[] = array( 'stone_name' => $name, 'stone_weight' => $stone_weight[$key], 'stone_rate' => $stone_rate[ $key ] );
    }

    return $result;
}

print_r($result);

Output:

Array
(
    [0] => Array
        (
            [stone_name] => ruby
            [stone_weight] => 112
            [stone_rate] => 1000
        )

    [1] => Array
        (
            [stone_name] => diamond
            [stone_weight] => 223
            [stone_rate] => 2500
        )

    [2] => Array
        (
            [stone_name] => catseye
            [stone_weight] => 445
            [stone_rate] => 670
        )

)

DEMO

Upvotes: 1

Related Questions