简体   繁体   中英

Create json From given array data

i have below array data and iwant json data from this array.

Array Object Data

[
    0=>{
       id: 1,
       s_id: 1,
       s_name: 'test 1'
    },
    1=>{
       id: 2,
       s_id: 2,
       s_name: 'test 2'
    },
    2=>{
       id: 3,
       s_id: 1,
       s_name: 'test 1'
    },
    3=>{
       id: 3,
       s_id: 2,
       s_name: 'test 2'
    }
]

i want to get this way

{
    0=>{
        id:1,
        s_data: {
            s_id: 1,
            s_name: 'test 1'
        }
    },
    1=>{
        id:2,
        s_data: {
            s_id: 2,
            s_name: 'test 2'
        }
    },
    3=>{
        id:3,
        s_data:{
            {
                s_id: 1,
                s_name: 'test 1'
            },
            {
                s_id: 2,
                s_name: 'test 2'
            }
        }
    }
}

Tried Code

foreach($data as $value){
    $arr[$value->id] =[ 
        'id' => $value->id,
        's_data'=>  [
            's_id'=>$value->s_id,
            's_name'=>$value->s_name
        ]
    ];
}

same id data in one obeject like id 3 has two s_id data so it get in one object

Use this foreach loop :

$res = [];  
$tmp = [];   

foreach($data as $value){

    // new ID
    if(!isset($tmp[$value->id])) {
        $tmp[$value->id] =[ 
            'id' => $value->id,
            's_data'=> []
        ];
    }

    // add new dataset to defined ID
    $tmp[$value->id]['s_data'][] = [ 's_id'=>$value->s_id, 's_name'=>$value->s_name];
}

// index start from 0
foreach($tmp as $obj){
    $res[] = $obj;
}

// create new JSON
json_encode($res);

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM