Fadly Dzil
Fadly Dzil

Reputation: 2206

Unite into one array based array from explode string in php

I have a lot of array based explode a string like this :

$size = explode(",", $row->SIZE);
$coil_no = explode(",", $row->COIL_NO);
$net = explode(",", $row->NET);
$gross = explode(",", $row->GROSS);
$contract_no = explode(",", $row->CONTRACT_NO);
$location = explode(",", $row->LOCATION);

How can I unite those array into one multidimensional array ?

I have try like this :

foreach ($size as $value) {
            foreach ($coil_no as $coil) {
                $detail[] = array(
                    "coil_no" => $coil,
                    "size" => $value
                );
            }
        }

you know the result the looping is loop weird, I need more elegant array, like

foreach ($unite_array as $row) :
    echo "<tr> $row->size </tr>" ;
endforeach;

What the best way to unite those array ?

Upvotes: 1

Views: 49

Answers (1)

kamal pal
kamal pal

Reputation: 4207

You can write your own function which does the grouping on keys as required, see example below:

function array_group(){
    if(func_num_args() > 0) {
        $params = func_get_args();
        $result = array();
        foreach($params as $key => $param) {
            foreach($param['values'] as $k => $value) {
                $result[$k][$param['alias']] = $value;
            }
        }
        return $result;
    }
    return false;
}

$rows = array_group(
    array('alias' => 'size', 'values' => array(1,2,3,4,5)),
    array('alias' => 'coil_no', 'values' => array(6,7,8,9,10)),
    array('alias' => 'net', 'values' => array(11,12,13,14,15)),
    array('alias' => 'gross', 'values' => array(16,17,18,19,20)),
    array('alias' => 'contract_no', 'values' => array(21,22,23,24,25)),
    array('alias' => 'location', 'values' => array(26,27,28,29,30))
);
print_r($rows);

And you can access it like:

foreach ($rows as $row) :
    echo "<tr> {$row['size']} </tr>" ;
endforeach;

Upvotes: 1

Related Questions