【问题标题】:Store object into array and group all array with the same value in PHP将对象存储到数组中并在PHP中将所有具有相同值的数组分组
【发布时间】:2018-04-30 21:21:56
【问题描述】:

我现在正在处理数组,我需要根据值来安排它。

{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "question": "sample question"
                },
            ]
        }
    }

我需要做的是将此对象存储到数组中,并根据段名对所有问题进行分组,如下所示:

{
    "data":[
         {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role "
                    "question_collection": [
                        {
                            "id": 4,
                            "question": "How old are you?"
                        }
                    ]


                },
                {
                    "segment_name": "360 Segments",
                    "question_collection":[
                        {
                           "id": 1,
                           "question": "What is your food?"
                        },
                        {
                             "id": 2,
                            "question": "sample question"
                         }
                    ] 
                },

            ]
        }
    ]
}

这就是我尝试做的:

 $array_value =[];       
        foreach ($query AS $key => &$data) {
            $array_value['id'] = $data['id'];
            $array_value['title'] = $data['title'];
            $array_value['emp_position'] = $data['position'];
            $array_value['rating'] = $data['rating_count'];                                  

            if ( is_array($data) ) {
               $array_value['segments'][$key]['segment_name'] = $data['segment'];                                  
               $array_value['segments'][$key]['question'] = $data['question'];                                  
            } 

        }

【问题讨论】:

  • 您可以将segments作为集合,然后使用集合的groupBy功能。
  • 您需要更改您的预期输出,因为对象/数组不能包含重复键。 "question_collection":[ { "question": "What is your food?" }, { "question": "sample question" } ]
  • @Bluetree 我想我很幸运你找到了我的问题。我需要从以前更改我的数组。希望你能再次帮助我解决这个问题。 :))))
  • @B.Desai 是的,你的权利。让我更新我上面的帖子
  • @alyssa 在你的 question_collection id 中。是来自$data['id']吗?

标签: php arrays laravel object


【解决方案1】:

如下所示:-

<?php

$json = '{
        "data": {
            "id": 2,
            "title": "second evaluation form",
            "emp_position": "System Architecture",
            "rating": 5,
            "segments": [
                {
                    "segment_name": "Job Role ",
                    "id": 4,
                    "question": "How old are you?"
                },
                {
                    "segment_name": "360 Segments",
                    "id": 1,
                    "question": "What is your food?"
                },
                {
                    "segment_name": "360 Segments",
                    "id": 2,
                    "question": "sample question"
                }
            ]
        }
    }
';

$query = json_decode($json,true);

$segment_array = [];
foreach($query['data']['segments'] as $arr){
  $segment_array[$arr['segment_name']]['segment_name'] = $arr['segment_name'];
  $segment_array[$arr['segment_name']]['question_collection'][] = ['id'=>$arr['id'],'question'=>$arr['question']] ;
}

$query['data']['segments'] = array_values($segment_array);

echo json_encode($query,JSON_PRETTY_PRINT);

输出:- https://eval.in/902194

【讨论】:

  • 嗨,感谢您的回复 :))) 您的代码几乎可以工作,但我在合并到我的原始数组时遇到问题
  • @AlyssaAndrea 我已经完全编辑了我的答案。请现在检查。希望它对你有用。
  • @AlyssaAndrea 很高兴为您提供帮助:):)
【解决方案2】:

在这里试试我的答案。我刚刚编辑了您现有的代码,因此您不会混淆那么多。这里没什么好解释的。我在评论中加入了一些解释。

代码

$array_value =[];       
foreach ($query AS $key => &$data) {
    $array_value['id'] = $data['id'];
    $array_value['title'] = $data['title'];
    $array_value['emp_position'] = $data['position'];
    $array_value['rating'] = $data['rating_count'];                                  

    if ( is_array($data) ) {

        // Check if segment is already added
        $has_segment = false;
        $segment_key = null;

        foreach($array_value['segments'] as $key2 => $val){
            //If segment is already added get the key
            if($val['segment_name'] == $data['segment']){
                $segment_key = $key2;
                $has_segment = true;
                break;
            }
        }
        // if segment does not exists. create a new array for new segment
        if(!$has_segment){
            $array_value['segments'] = array();
        }
        // If new segment, get the index
        $segment_key = count($array_value['segments']) - 1;

        // If new segment, create segment and question collection array
        if(!array_key_exists('question_collection', $array_value['segments'][$segment_key])){
            $array_value['segments'][$segment_key]['segment_name'] = $data['segment'];    
            $array_value['segments'][$segment_key]['question_collection'] = array();
        }
        //Add the id for question collectiona rray
        $array_value['segments'][$segment_key]['question_collection'][] = array(
            "id" =>  $data['question_id'],
            "question" =>  $data['question']
        );            
    }
}

【讨论】:

    【解决方案3】:

    试试这个解决方案,您可以按数组循环并对所有键进行分组

    $json = '{
            "data": {
                "id": 2,
                "title": "second evaluation form",
                "emp_position": "System Architecture",
                "rating": 5,
                "segments": [
                    {
                        "segment_name": "Job Role ",
                        "question": "How old are you?"
                    },
                    {
                        "segment_name": "360 Segments",
                        "question": "What is your food?"
                    },
                    {
                        "segment_name": "360 Segments",
                        "question": "sample question"
                    }
                ]
            }
        }';
    
    $data = json_decode($json,true);
    
    
    $segments = $data['data']['segments'];
    $new_segemnts = array();
    foreach($segments as $segemnt)
    {
        $key = $segemnt['segment_name'];
    
        $new_segemnts[$key]['segment_name']=$segemnt['segment_name'];
        $new_segemnts[$key]['question_collection'][]=array("question"=>$segemnt['question']);
    
    }
    $data['data']['segments'] = array_values($new_segemnts);
    echo json_encode($data,JSON_PRETTY_PRINT);
    

    DEMO

    【讨论】:

      【解决方案4】:

      收集功能可能会帮助您找到解决方案。

      $json = '{"data":{"id":2,"title":"second evaluation form","emp_position":"System Architecture","rating":5,"segments":[{"segment_name":"Job Role ","question":"How old are you?"},{"segment_name":"360 Segments","question":"What is your food?"},{"segment_name":"360 Segments","question":"sample question"}]}}';
      
          $array = json_decode($json, true);
          $coll = collect($array['data']['segments']);
          $coll = $coll->groupBy('segment_name');
          dump($coll);
      

      希望对您有所帮助。如果有任何问题,请告诉我

      【讨论】:

      • 感谢您的回复 :))) 当我尝试您的代码时,我不知道为什么我总是遇到 json_decode 问题。" json_decode() 期望参数 1 是字符串,给定数组"跨度>
      • 确保 $json 是一个字符串,您可以使用 gettype() 检查变量类型
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2020-02-08
      • 2017-10-29
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多