-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
    )
)
4
  • 2
    Use simple foreach loop and some logic to merge your array Commented Nov 28, 2019 at 4:11
  • please make simple code to example Commented Nov 28, 2019 at 4:14
  • php.net/manual/de/control-structures.foreach.php Commented Nov 28, 2019 at 4:23
  • @axhxs You can check the given example Commented Nov 28, 2019 at 5:26

2 Answers 2

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

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'];

     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.