<?php
/*
- Obey PSR coding standards as much as possible (I choose to disobey Joomla's suggested standards when they defy PSR). Most importantly, read PSR-12.
- `is_array() || is_object()` seems sensibly replaced with `is_iterable()`. Are you deliberately not returning anything in this condition branch?
- Use Joomla's database querying methods for consistency and usability (since you are sharing your snippet with the world).
Code:
function getJCFields($srcId, $fieldId = null, $dbfields = null, $context = null)
{
$context = $context ?? 'com_content.article';
if (is_iterable($srcId) ) {
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jfields = FieldsHelper::getFields($context, $srcId, true);
} elseif (ctype_digit((string)$srcId)) {
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($dbfields ?? "id,label,value")
->from("#__fields f")
->innerJoin("#__fields_values fv ON f.id = fd.field_id")
->where("context = " . $db->qn($context))
->where("fv.item_id = " . (int)$srcId);
if ($fieldId) {
$query->where("f.id = " . (int)$fieldId);
}
$db->setQuery($query);
return fieldId ? $db->loadObject() : $db->loadObjectList();
}
}
Regarding your displaying of the data...
- With your view implementation, the default glue for `implode()` is an empty string and this parameter can be omitted to achieve the same effect. So `implode('', $cell)` becomes `implode($cell)`.
- But if you are imploding with no glue, then you might as well just directly concatenate to your output string to avoid adding temporary variables to the scope.
- Call `getJCFields()` only once per loop iteration
Code:
$fieldTable = '<div class="tbl chart">';
$srcid = ['id' => 24, 'catid' => 5];
$fields = [2, 3, 4, 5, 6, 8];
foreach ($fields as $fid) {
$jcField = getJCFields($srcid, $fid);
if ($jcField) {
$fieldTable .= sprintf(
'<div class="tr">
<div class="cell lbl">%s</div>
<div class="cell val">%s</div>
</div>',
$jcField->label,
$jcField->value
);
}
}
$fieldTable .= '</div>';
*/