user7719185
user7719185

Reputation:

Store object into array and group all array with the same value in PHP

I'm working on array right now and I need to arrange this based on value.

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

What I need to do is to store this object into array and group all question based on segment_name like this:

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

            ]
        }
    ]
}

And this is what I've tried to do:

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

        }

Upvotes: 3

Views: 141

Answers (4)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Do it like below:-

<?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);

OUTPUT:- https://eval.in/902194

Upvotes: 1

JJJJ
JJJJ

Reputation: 1358

Here try my answer. I've just editted your existing code so you won't confuse that much. Nothing much to explain here. I included some explaination in my comment.

CODE

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

Upvotes: 1

B. Desai
B. Desai

Reputation: 16436

Try this solution, You can loop by array and group all keys

$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

Upvotes: 1

Rohit shah
Rohit shah

Reputation: 819

Collection function might help you find your solution.

$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);

Hope this helps you.Let me know if any problem

Upvotes: 2

Related Questions