phpsqljoomlaforeachk2

Illegal string offset when using foreach related to SQL Statement


Why am I getting this error when trying to access any of the array keys using the following?

$product_cat = '22';
$db = JFactory::getDbo();
$query = $db->getQuery( true );
$query->select( $db->quoteName( array( 'name', 'alias', 'parent' ) ) );
$query->from( $db->quoteName( '#__k2_categories' ) );
$query->where( $db->quoteName( 'parent' )." = " .$product_cat );
$db->setQuery( $query );
$row = $db->loadObjectList();
print_r($row);
foreach ($row as $value) {
    foreach($value as $result) {
        echo '<ul>';
        echo '<li><a href="#">' . $result['name'] . '</a></li>';
        echo '</ul>';
    }
}

The following array is being returned:

Array (
[0] => stdClass Object ( [name] => Stimulation Chemicals [alias] => stimulation-chemicals [parent] => 22 )
[1] => stdClass Object ( [name] => Cementing Chemicals [alias] => cementing-chemicals [parent] => 22 )
[2] => stdClass Object ( [name] => Improved Oil Recovery [alias] => improved-oil-recovery [parent] => 22 )
[3] => stdClass Object ( [name] => Drilling Fluid Additives [alias] => drilling-fluid-additives [parent] => 22 )
[4] => stdClass Object ( [name] => Solvents and Surfactants [alias] => solvents-and-surfactants [parent] => 22 )
[5] => stdClass Object ( [name] => Coil Tubing Chemicals [alias] => coil-tubing-chemicals [parent] => 22 )
[6] => stdClass Object ( [name] => Production Chemicals [alias] => production-chemicals [parent] => 22 ) )

So I'm not sure what's happening, I'm simply trying to access 'name, 'alias' and 'parent' and spit them out in different places in a echoed html string. Any ideas?


Solution

  • Try this:

    foreach ($row as $value) {
       echo '<ul>';
       echo '<li><a href="#">' . $value->name . '</a></li>';
       echo '<li><a href="#">' . $value->alias . '</a></li>';
       echo '<li><a href="#">' . $value->parent . '</a></li>';
       echo '</ul>';
    }