I have a large JSON file with more than 200 items. There are 5 groups data in it. each group has at least 30 items. I distinguish them using "p" tag, like "p":"1","p":"2","p":"3","p":"4","p":"5" in the json data. Now I want get 2 items from each group and total for 10 items with a random orders.
For an easy explanation, I set some simple data like below. “p”:”1″ have 4 items in its group, “p”:”2″ have 4 items in its group.
Now how to make get 2 items from "p":"1" and 2 items with "p":"2" with a random orders?
$json = <<<ETO
[
{
"a":"apple",
"p":"1"
},
{
"a":"orange",
"p":"1"
},
{
"a":"pear",
"p":"1"
},
{
"a":"banana",
"p":"1"
},
{
"a":"Chauli",
"p":"2"
},
{
"a":"Carrot",
"p":"2"
},
{
"a":"Lettuce",
"p":"2"
},
{
"a":"Potato",
"p":"2"
}
]
ETO;
$data = json_decode($json);
shuffle($data);// some shuffle like this is very ugly...
foreach($data as $row){
$aoo = 1;
$boo = 1;
if($row->p==1){
echo $row->p.': '.$row->a.'<br />';
$aoo++;
if($aoo==2){
break;
}
}
if($row->p==2){
echo $row->p.': '.$row->b.'<br />';
$boo++;
if($boo==2){
break;
}
}
}
I need get the result like:
orange ("p":"1") Carrot ("p":"2") pear ("p":"1") Lettuce ("p":"2")
Lettuce ("p":"2") banana ("p":"1") Apple ("p":"1") Chauli ("p":"2")
In one word, get 2 Vegetables and 2 Fruits combine for a mixed orders. Thanks.
1 Answer