3

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

        }
9
  • You can make segments as collection and then use groupBy function of collection. Commented Nov 17, 2017 at 7:02
  • You need to change your expected output as object/array can not contain duplicate key. "question_collection":[ { "question": "What is your food?" }, { "question": "sample question" } ] Commented Nov 17, 2017 at 7:02
  • @Bluetree I think I'm lucky that you found my question. I need to change my array from before. hope you could help me with this one again. :)))) Commented Nov 17, 2017 at 7:03
  • @B.Desai yeah your right. let me update my post above Commented Nov 17, 2017 at 7:06
  • @alyssa in your question_collection id . is it coming from $data['id']? Commented Nov 17, 2017 at 7:14

4 Answers 4

2

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

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

2 Comments

thanks for your response :))) As I tried your code I dunno why I'm always having a problem with json_decode." json_decode() expects parameter 1 to be string, array given"
make sure that $json is a string you can check it using gettype() to check variables type
1

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

3 Comments

hi thanks for response :))) your code almost work but im having a problem on merging to my original array
@AlyssaAndrea i have edited my answer completely.Please check now. Hope it will worked for you.
@AlyssaAndrea glad to help you :):)
1

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

Comments

1

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

Comments

Your Answer

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