猿问

在php中组合值数组

我在根据 id 组合值时遇到问题。


我有这样的数据:


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

    )

)

然后,我想[id_values]根据 id 组合,所以我可以在php中获取这样的数据


Array(

   [0] => Array(

      [id] => 1

      [id_name] => a

      [id_vales] => 5, 4

    )

    [1] => Array(

      [id] => 3

      [id_name] => b

      [id_vales] => 4, 3

    )

)


Qyouu
浏览 115回答 2
2回答

慕容森

您可以使用以下示例合并您的数组<?php$mainArray = array(array('id' => 1, 'id_name' => 'a', 'id_vales' => 5),&nbsp;&nbsp; &nbsp; &nbsp; array('id' => 1,'id_name' => 'a','id_vales' => 4),&nbsp; &nbsp; &nbsp; array('id' => 3, 'id_name' => 'b','id_vales' => 4),&nbsp; &nbsp; &nbsp; array('id' => 3,'id_name' => 'b','id_vales' => 3));$result = array();$tempArray = array();foreach($mainArray as $key => $value){&nbsp; &nbsp; if(isset($tempArray[$value['id']]))&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $tempArray[$value['id']] .= ", ".$value['id_vales'];&nbsp; &nbsp; &nbsp; &nbsp; $result[] = array('id' => $value['id'], 'id_name' => $value['id_name'], 'id_vales' => $tempArray[$value['id']]);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $tempArray[$value['id']] = "".$value['id_vales'];&nbsp; &nbsp; }}echo "<pre>";print_r($result);?>您可以在此处找到运行示例https://paiza.io/projects/3sS3GXH7GHqoipH8k-YtBQ输出:Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id] => 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id_name] => a&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id_vales] => 5, 4&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id] => 3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id_name] => b&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [id_vales] => 4, 3&nbsp; &nbsp; &nbsp; &nbsp; ))

慕标5832272

我为你创建了一个数组。从此数组中,您可以轻松创建数组并获得结果。$data = array();&nbsp; &nbsp; &nbsp;foreach($array as $key=>$value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data[$value['id']]['id'] = $value['id'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data[$value['id']]['id_vales'][] = $value['id_vales'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $data[$value['id']]['id_name'] = $value['id_name'];&nbsp; &nbsp; &nbsp;}
随时随地看视频慕课网APP
我要回答