-2

i have problem to combine values based on id.

I have data like this :

Array(
     [0] => Array(
        [id] => 1,
        [id_name] => a
        [id_vales] => 5
     )
     [1] => Array(
        [id] => 1
        [id_name] => a
        [id_vales] => 4
     )
     [2] => Array(
        [id] => 3
        [id_name] => b
        [id_vales] => 4
    )
    [3] => Array(
        [id] => 3
        [id_name] => b
        [id_vales] => 3
    )
)

then, i want combine [id_values] based on id, so i can get data like this in php

Array(
   [0] => Array(
      [id] => 1
      [id_name] => a
      [id_vales] => 5, 4
    )
    [1] => Array(
      [id] => 3
      [id_name] => b
      [id_vales] => 4, 3
    )
)
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
axhxs
  • 15
  • 2

2 Answers2

1

You can use the following example to merge your array

<?php

$mainArray = array(array('id' => 1, 'id_name' => 'a', 'id_vales' => 5), 
      array('id' => 1,'id_name' => 'a','id_vales' => 4),
      array('id' => 3, 'id_name' => 'b','id_vales' => 4),
      array('id' => 3,'id_name' => 'b','id_vales' => 3)
);

$result = array();
$tempArray = array();
foreach($mainArray as $key => $value)
{
    if(isset($tempArray[$value['id']]))
    { 
        $tempArray[$value['id']] .= ", ".$value['id_vales'];
        $result[] = array('id' => $value['id'], 'id_name' => $value['id_name'], 'id_vales' => $tempArray[$value['id']]);
    }
    else
    {
        $tempArray[$value['id']] = "".$value['id_vales'];
    }
}
echo "<pre>";
print_r($result);
?>

You can find running example here https://paiza.io/projects/3sS3GXH7GHqoipH8k-YtBQ

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [id_name] => a
            [id_vales] => 5, 4
        )

    [1] => Array
        (
            [id] => 3
            [id_name] => b
            [id_vales] => 4, 3
        )

)
Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40
1

I have created an array for you. from this array you can easily create your array and get the result.

$data = array();
     foreach($array as $key=>$value){
            $data[$value['id']]['id'] = $value['id'];
            $data[$value['id']]['id_vales'][] = $value['id_vales'];
            $data[$value['id']]['id_name'] = $value['id_name'];

     }
Amit Sharma
  • 1,775
  • 3
  • 11
  • 20