这是我的模特:
function item_attributes_data($id){
$query=$this->db->query("SELECT attributes.attribute_text,item_attributes.attr_value,item_attributes.cost
FROM attributes
INNER JOIN item_attributes
ON attributes.id=item_attributes.attr_id
where item_attributes.item_id=".$id);
return $query->result();
}
这是我的控制器:
function item_attributes()
{
header('Access-Control-Allow-Origin:*');
$id=$this->uri->segment(3);
$this->load->model('orderapp_model');
$query_result=$this->orderapp_model->item_attributes_data($id);
echo json_encode($query_result);
}
我将数据检索为
url=localhost/ordertakeadmin/index.php/orderapp/item_attributes/
我得到了JSON数组如下:
options = [{
"attribute_text": "VEHICLE",
"attr_value": "Truck",
"cost": "897.00"
}, {
"attribute_text": "MATERIAL",
"attr_value": "Steel",
"cost": "385.00"
}, {
"attribute_text": "SIZE",
"attr_value": "Medium",
"cost": "254.00"
}]
但我想将数据构建为
options = [{
attribute_text: "SIZE",
choices: [{
attr_value: "Medium",
cost: 254.00
}, {
attr_value: "Small",
cost: 154.00
}, {
attr_value: "Large",
cost: 280.00
}]
}, {
attribute_text: "MATERIAL",
choices: [{
attr_value: "Steel",
cost: 385.00
}, {
attr_value: "Carbon Fiber",
cost: 285.00
}, ]
}, {
attribute_text: "VEHICLE",
choices: [{
attr_value: "Truck",
cost: 897.00
}, {
attr_value: "Car",
cost: 122.00
}]
}];
这是我的数据库:
attribute_text attr_value成本
尺寸大1500.00
VEHICLE Truck 897.00
材料钢385.00
SIZE Medium 254.00
VEHICLE Car 855.00
VEHICLE吉普车875.00
材料铅897.00
怎么可能?
答案 0 :(得分:0)
我试过破译你的问题,我想你想要这样的事情:
function item_attributes_data($id){
// first get your attributes
$query=$this->db->query("SELECT id, attributes.attribute_text FROM attributes");
$attributes = $query->result();
$finalResult = array();
// then get the items for each attribute
foreach($attributes as $attribute) {
// fetch the items
$itemsQuery = $this->db->query("SELECT attr_value, cost FROM item_attributes WHERE attr_id=" . $attribute['id']);
$items = $itemsQuery->result();
$finalResult[] = array( "attribute_text" => $attribute["attribute_text"], "choices" => $items );
}
return $finalResult;
}