简体   繁体   中英

Array to string conversion error while using foreach in php in joomla article

<?php
    $db = JFactory::getDbo();

    $query = $db->getQuery(true);

    $query->select($db->quoteName(array('ques', 'options')));
    $query->from($db->quoteName('logical_ques'));

    $db->setQuery($query);

    $result = $db->loadRowList();

    print_r($result);

    foreach($result as $key => $value)
    {
        echo " ". $value;
    }
?>

Hello everyone, I'm creating a website in Joomla and I want to display some values from the database into the article but not in array form and for this I've used foreach but it's giving me Array to string conversion error

$value seems to be an array. Please check using var_dump. Echoing an array gives this error.

The array_values seems to be array. So create a recursive function to return string from your array. The code should be something like this

<?php

$db = JFactory::getDbo();

$query = $db->getQuery(true);

$query->select($db->quoteName(array('ques', 'options')));
$query->from($db->quoteName('logical_ques'));

$db->setQuery($query);

$result = $db->loadRowList();

print_r($result);

if (is_array($result)) {
    echo arrayToString($result);
} else {
    echo $result;
}

function arrayToString($array)
{ 
    foreach($array as $key => $value)
    {
        if (is_array($value))
        {
            $res .= arrayToString($value);
        } else {
            $res .= " ". $value;
        }
    }
    return $res;
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM