I am working with joomla k2 component and I am building another component based on it. Here I have a problem in accessing(parsing) k2 extra fields. Help will be appreciated.

The k2 extra field content in database is like this,

[{"id":"1","value":"500"},{"id":"2","value":"40Hrs"},{"id":"3","value":"1"}]

I searched k2 site and others and given answer as,

$this->item->extra_fields[0]->value; //needs to return 500

I tried in different ways but it wont work.

有帮助吗?

解决方案

Try this,

$str='[{"id":"1","value":"500"},{"id":"2","value":"40Hrs"},{"id":"3","value":"1"}]';
$vals=json_decode($str);
print_r($vals);

If you want to print 500,

echo $vals[0]->value; //prints 500

or want to loop it,

foreach($val as $v){
  echo $v->value;
}

其他提示

You can use the json_decode() function to decode it from a JSON string format to a PHP object.

Example:

$JSON = '[{"id":"1","value":"500"},{"id":"2","value":"40Hrs"},{"id":"3","value":"1"}]';

$obj = json_decode($JSON); 

echo $obj[0]->value;

Depending on where you are, how you use extra fields can change.

In item views - $this->item->extra_fields[id]->value;

In K2 content module - $item->extra_fields[id]->value;

In both cases you replace the id with the corresponding number of the extra field you are trying to use. Numbering starts at 0. These are treated as typical PHP variables. You might want to post some code so we can see what you are trying to do.

If your extra_fields value is being returned as a string (unparsed) instead of an array of objects its possible its due to configuration, because extra_fields are parsed (or not) based on it.

//Extra fields
if (($view == 'item' && $item->params->get('itemExtraFields'))
   || ($view == 'itemlist' && ($task == '' || $task == 'category') && $item->params->get('catItemExtraFields'))
   || ($view == 'itemlist' && $task == 'tag' && $item->params->get('tagItemExtraFields')) 
   || ($view == 'itemlist' && ($task == 'search' || $task == 'date') && $item->params->get('genericItemExtraFields')))
{
    $item->extra_fields = K2ModelItem::getItemExtraFields($item->extra_fields);
}

When displaying an item in a category list, you can enable extra_fields (catItemExtraFields) by editing the category and under Item view options in category listings click on Show for the Extra Fields item.

When in an item view, you can enable extra_fields (itemExtraFields) by editing the category and under Item view options click on Show for the Extra Fields item.

This should enable extra_fields parsing in category items listing and item view.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top