您好我有两个表属性和property_images我使用以下查询连接这些表:
function get_residential(){
$query = $this->db->query("SELECT
property.ID,
property.property_name,
property.property_slug,
property.property_size,
property.property_beds,
property.property_bath,
property.property_garage,
property.property_type,
property.property_state,
property.property_price,
property.property_address,
property.property_description,
property.date_created,
property.active,
property_image.image_name
FROM
property AS property
INNER JOIN property_images AS property_image ON property.ID = property_image.image_id
WHERE property.property_type = 'Residential'
GROUP BY property.ID
ORDER BY property.ID");
return $query->result('array');
}
目前我能够输出所有属性描述信息但不能输出图像,我将如何在视图中输出与属性相关的图像?
答案 0 :(得分:0)
我们假设这是您从数据库获得的属性数据。
$property_data = //the following array
array(
[0] => array ('property_id' => 1, 'property_name' => 'mansion'),
[1] => array ('property_id' => 2, 'property_name' => 'brick house')
)
并假设这是数据库中的 property_image 数据
$property_image_data = //the following array
array(
[0] => array ('image_property_id' => 1, 'image_url' => 'some url 1'),
[1] => array ('image_property_id' => 1, 'image_url' => 'some url 2'),
[2] => array ('image_property_id' => 1, 'image_url' => 'some url 3'),
[3] => array ('image_property_id' => 2, 'image_url' => 'some url 4'),
[4] => array ('image_property_id' => 2, 'image_url' => 'some url 5'),
[5] => array ('image_property_id' => 2, 'image_url' => 'some url 6'),
)
你想做的是这样的事情
$property_hash_table = array();
for ($i = 0; $i < count($property_data); ++$i) {
$property_id = $property_data[$i]['property_id'];
$property_data[$i]['image_urls'] = array(); //we want an array for all of the associated urls for this property
$property_hash_table[$property_id] = $property_data[$i];
}
现在我们通过其唯一ID为每个属性提供了一个哈希表。然后我们可以遍历图像并将它们添加到正确的属性
for ($i = 0; $i < count($property_data); ++$i) {
$image_property_id = $property_image_data[$i]['image_property_id'];
$image_url = $property_image_data[$i]['image_url'];
if(array_key_exists($image_property_id, $property_hash_table)){
//we have a product in our hash table that this image belongs to
array_push($property_data[$image_property_id]['image_urls'], $image_url);
}
}
最终结果(哈希表中的数据)将如下所示
array(
// notice the key here ([1]) is actually the property id from the database
[1] => array (
'property_id' => 1,
'property_name' => 'mansion',
'image_urls' => array(
[0] => 'some url 1',
[1] => 'some url 2',
[2] => 'some url 3'
)
),
[2] => array (
'property_id' => 2,
'property_name' => 'brick house',
'image_urls' => array(
[0] => 'some url 4',
[1] => 'some url 5',
[2] => 'some url 6'
)
)
)