在PHP中将对象存储到数组中,并以相同值对所有数组进行分组

3

我正在处理数组,需要根据值进行排序。

{
        "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"
                },
            ]
        }
    }

我需要做的是将此对象存储到数组中,并根据segment_name分组所有问题,如下所示:
{
    "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'];                                  
            } 

        }

@alyssa,在你的question_collection中,id是来自于$data['id']吗? - Bluetree
从哪里冒出这些id的?我一点头绪都没有。请告诉我们。 - Alive to die - Anant
@AlivetoDie 我需要添加Id以避免在使用ngFor循环时在Angular中出现错误。 - user7719185
@Bluetree 不是的,data['id'] 是用于评估的,而问题中的 id 是来自问题表的。 - user7719185
@AlyssaAndrea,在你的输入中没有ID,但在输出中突然添加了?我们怎么知道它来自哪里或者你使用了什么逻辑来显示在你的预期结果中。你检查过我的答案吗? - Alive to die - Anant
显示剩余4条评论
4个回答

2

集合函数可能会帮助您找到解决方案。

$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为字符串,但给出了数组" - user7719185
确保 $json 是一个字符串,您可以使用 gettype() 函数来检查变量的类型。 - Rohit shah

1

尝试这个解决方案,您可以通过数组循环并将所有键分组

$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


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

嗨,感谢回复:))) 你的代码几乎可以工作,但我在合并到我的原始数组时遇到了问题。 - user7719185
@AlyssaAndrea 我已经完全编辑了我的答案。请现在检查一下。希望它对你有用。 - Alive to die - Anant
@AlyssaAndrea 很高兴能帮助你 :):) - Alive to die - Anant

1

请看我的回答。我刚刚编辑了你现有的代码,让你不会感到太困惑。这里没有什么需要解释的。我在我的注释中包含了一些说明。

代码

$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']
        );            
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接