ace
ace

Reputation: 11

Laravel: Combine values in array

can I ask for your help? I have values in the array and I want to combine them to become one value. I want a result that 'gendesc' 'dmdnost' 'stredesc' 'formdesc' 'rtedesc' will be in one column. Thanks.

 foreach($data as $item){
        $tmp = array();

        $tmp_item = (array) $item;

        $tmp['description'] = $tmp_item['gendesc'];
        $tmp['m1'] = $tmp_item['dmdnost'];
        $tmp['m2'] = $tmp_item['stredesc'];
        $tmp['m3'] = $tmp_item['formdesc'];
        $tmp['m4'] = $tmp_item['rtedesc'];


        $final_data [] = $tmp;

    }
    print_r($final_data);

Upvotes: 1

Views: 62

Answers (3)

Jithesh Jose
Jithesh Jose

Reputation: 1814

Try this,

$i =0;
foreach($data as $item)
{
$tmp = [];
$tmp[$i]['description'] = $item['gendesc'];
$tmp[$i]['m1'] = $item['dmdnost'];
$tmp[$i]['m2'] = $item['stredesc'];
$tmp[$i]['m3'] = $item['formdesc'];
$tmp[$i]['m4'] = $item['rtedesc'];
$i++;
}
print_r($tmp);

Upvotes: 1

daremachine
daremachine

Reputation: 2788

You want this?

foreach($data as $item){
    $tmp = array();

    // ver.1
    $tmp['description'] = $item['gendesc']
      . $item['dmdnost']
      . $item['stredesc']
      . $item['formdesc']
      . $item['rtedesc'];

    // ver.2 also you can use one-line shortcut with implode instead of ver.1
    $tmp['description'] = trim(implode(" , ", $item));

    $final_data[] = $tmp;

}
print_r($final_data);

Upvotes: 1

Ryan Nghiem
Ryan Nghiem

Reputation: 2438

Can you try

foreach($data as $item){
    $tmp_item = (array) $item;

    $tmp = $tmp_item['gendesc']
    . ' ' . $tmp_item['dmdnost']
    . ' ' . $tmp_item['stredesc']
    . ' ' . $tmp_item['formdesc']
    . ' ' . $tmp_item['rtedesc'];


    $final_data[] = array('description' => $tmp);

}
print_r($final_data);

Upvotes: 1

Related Questions