我有一个检索数组的 SQL 语句,并且我想访问该数据。
My SQL(Joomla 语法):
$fields->select(array('a.virtuemart_product_id',
'a.virtuemart_custom_id', 'a.virtuemart_custom_id', 'v.value', 'r.intval'))
->from('#__virtuemart_product_customfields AS a')
->join('INNER', '#__virtuemart_product_custom_plg_param_ref AS r
ON (a.virtuemart_custom_id = r.virtuemart_custom_id
AND a.virtuemart_product_id = r.virtuemart_product_id)')
->join('INNER', '#__virtuemart_product_custom_plg_param_values
AS v ON (r.val = v.id)')
->where('a.virtuemart_product_id='.$vehicle_id)
->order('a.virtuemart_custom_id ASC');
$db->setQuery($fields);
// Load the results as a list of stdClass objects.
$customs = $db->loadObjectList();
$customs
的我的数组输出作为一个示例
Array
(
[0] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 38
[value] => 2200 TD
[intval] => 0
)
[1] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 39
[value] => 6 Berth
[intval] => 0
)
[2] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 40
[value] => Coachbuilt
[intval] => 0
)
[3] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 41
[value] => 30990
[intval] => 0
)
[4] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 42
[value] => MX08 JVR
[intval] => 0
)
[5] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 43
[value] => Manual
[intval] => 0
)
[6] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 44
[value] => L23'7''
[intval] => 0
)
[7] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 47
[value] => 2008
[intval] => 0
)
[8] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 53
[value] => Front Lounge
[intval] => 0
)
[9] => stdClass Object
(
[virtuemart_product_id] => 675
[virtuemart_custom_id] => 54
[value] => UNDER 3500kg
[intval] => 0
)
)
上面是在 foreach
中,只需从数据库中选择所有产品即可。 $vehicle_id
最终的目标是通过virtualmart_custom_id从数组中输出XML,所以:
<Example> [value where virtuemart_custom_id = 1 ] </Example>
<ExampleTwo> [value where virtuemart_custom_id = 2] </ExampleTwo>
问题:如果我定位 $customs[1],如果行为空,数据可能会发生变化..不好?即 echo $customs[1]->value。
在“选择”我需要的 virtuemart_custom_id
的同时实现上述输出的最佳方式是什么?
最佳答案
foreach($customs as $key=>$object){
if($object->virtuemart_custom_id==1){
//<Example> [value where virtuemart_custom_id = 1 ] </Example>
echo $object->value;
}
}
事实上,您可以对其进行改进,并拥有一个包含所有值的新数组,就像这样
$values=array();
foreach($customs as $key=>$object){
$values[$object->virtuemart_custom_id] = $object->value;
}
print_r($values); // This will give you all values indexed on their custom ids
关于php - 如何访问数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26505013/