1

sorry if my question is little confusing. the following is my json output form mysql:

[{"ID":"2","BatchID":"0","Day":"Sunday","Low":"01:15","High":"02.45","Mid":    "01:30 01:45 02:00 02:15 02:30"},    {"ID":"1","BatchID":"0","Day":"Sunday","Low":"00.45","High":"00:30","Mid":"    01:30 01:45 02:00 02:15 02:30"}]

i want to use the day "sunday" in this case to merge both the objects to form something like this:

"Sunday":[
        {
            "low":"00:15",
            "high":"00.45",
            "mid":["00:30"]
        },
        {
            "low":"01:15",
            "high":"02.45",
            "mid":["01:30","01:45","02:00","02:15","02:30"]
        }

    ]

also, are there any tools that can help me make models in php for saving this in a db?

thanks in advance.

max

1
  • ps: my php object looks like this : Array ( [0] => stdClass Object ( [ID] => 2 [BatchID] => 0 [Day] => Sunday [Low] => 01:15 [High] => 02.45 [Mid] => 01:30 01:45 02:00 02:15 02:30 ) [1] => stdClass Object ( [ID] => 1 [BatchID] => 0 [Day] => Sunday [Low] => 00.45 [High] => 00:30 [Mid] => 01:30 01:45 02:00 02:15 02:30 ) ) Commented May 14, 2016 at 20:19

2 Answers 2

3

You can use something like :

$data = json_decode($mysql_data, true);
$res = [];
foreach ($data as $d)
{
    $add = ['low'  => $d['Low'],
            'high' => $d['High'],
            'mid'  => explode(' ', trim($d['Mid']))];
    if (!isset($res[$d['Day']]))
        $res[$d['Day']] = $add;
    else
        $res[$d['Day']][] = $add;
}
$pretty_data = json_encode($res);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Ebahi, you saved my entire night! :)) i removed the condition and it works like a charm ;) /* if (!isset($res[$d['Day']])) $res[$d['Day']] = $add; else */
1

You can reorganize it in PHP as the other answer suggests. You can also reorganize it in Javascript:

var values = [{"ID":"2","BatchID":"0","Day":"Sunday","Low":"01:15","High":"02.45","Mid":    "01:30 01:45 02:00 02:15 02:30"},    {"ID":"1","BatchID":"0","Day":"Sunday","Low":"00.45","High":"00:30","Mid":"    01:30 01:45 02:00 02:15 02:30"}];

var final = {};
values.forEach(function(element, index, array) {
    if (!final[element.Day]) 
        final[element.Day] = [];

    final[element.Day].push(
        {
            "low": element.Low,
            "high": element.High,
            "mid": element.Mid.split(" ")
        }
    );
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.