Search code examples
phparraysjsonjoomlaresultset

How to extract a single value from a json encoded database table column value in Joomla?


I'm trying to get an image url from Joomla via PHP/Sql Query. It's a multidimensional array or object, but I can't get the second dimensions.

What data type is that? Do I have to convert it somehow? I already tried "loadAssocList()" and "loadObjectList()", but both give me strange data.

How do I convert it to a multi-dimensional array, or even better, get access to the $r[images][intro_image] value? And why are the slashes escaped there?

Joomla DB Query like in Documentation:

$db = JFactory::getDbo();
$id = 9; //example
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__content');
$query->where('catid="'.$id.'"');

$db->setQuery((string)$query);
$res = $db->loadAssocList();
?>
<?php foreach($res as $r): ?>
<pre>
<?php print_r($r); ?>
</pre>
<?php endforeach; ?>

PHP Response Array:

[fulltext] => 
    [state] => 1
    [catid] => 9
    [created] => 2018-09-10 20:45:29
    [created_by] => 165
    [created_by_alias] => 
    [modified] => 2018-09-14 08:28:52
    [modified_by] => 165
    [checked_out] => 165
    [checked_out_time] => 2018-09-14 08:32:10
    [publish_up] => 2018-09-10 20:45:29
    [publish_down] => 0000-00-00 00:00:00
    [images] => {"image_intro":"images\/thumb_2017-28-04-Taspo.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/thumb_2017-28-04-Taspo.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}
    [urls] => {"urla":"\/images\/\/Presseartikel\/2017-28-04-Taspo-optimiert.pdf","urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}
    [attribs] => {"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}
    [version] => 5

I need to read data from this part of the array:

{"image_intro":"images\/thumb_2017-28-04-Taspo.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/thumb_2017-28-04-Taspo.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}

Solution

  • Images are in JSON format so you first need to decode that data.

    $images = json_decode($r['images']);
    print_r($images);
    

    then you can access image_intro using below code -

    $images->image_intro;