简体   繁体   中英

php echo from array_chunk as string

I want to echo an array_chunk as string, how do I do that ? here is the code

$rt = $this->db->query("SELECT id_reg_pd FROM 043104_kuliahmhs_20152_2a0dc380_temp");
$_datao = array_chunk($rt->result(), 3);
foreach($_datao as $batman => $robin) {
    print_r($robin);
}

I want echo id_reg_pd as string. I have tried tried :

echo $robin->id_reg_pd;

but get php error like this

A PHP Error was encountered
Severity: Notice
Message:  Trying to get property of non-object

Here the array from print_r($robin);

Array
(
    [0] => stdClass Object
        (
            [id_reg_pd] => 001be76b-4e58-4cea-96cf-fee2d8e0abdc
        )

    [1] => stdClass Object
        (
            [id_reg_pd] => 001d4fe5-73f5-4bae-b126-1f787ea0104e
        )

    [2] => stdClass Object
        (
            [id_reg_pd] => 002ab28b-e0b9-464a-89fb-12552512a5d0
        ) 
)

Loop over $robin and then check

foreach($robin as $value)
{
    echo $value->id_reg_pd;
}

try like this

   for($i=0;$i<count($_datao);$i++){ 
    $newarr = (array) $robin[$i];
    echo $newarr['id_reg_pd'];
  }

Sahil is incorrect. It is not true that you must use a for / foreach loop to achieve your desired result. array_column() works on an array of objects. If you can use a simple implode() call to convert your array to a string, then here is a simple one-liner:

Code ( Demo ):

$robin=[
    (object)['id_reg_pd'=>'001be76b-4e58-4cea-96cf-fee2d8e0abdc'],
    (object)['id_reg_pd'=>'001d4fe5-73f5-4bae-b126-1f787ea0104e'],
    (object)['id_reg_pd'=>'002ab28b-e0b9-464a-89fb-12552512a5d0']
];
//print_r($robin);  // uncomment to see for yourself
//var_export(array_column($robin,'id_reg_pd'));  // uncomment to see for yourself
echo implode(', ',array_column($robin,'id_reg_pd')); // implode with whatever glue you wish

Output:

001be76b-4e58-4cea-96cf-fee2d8e0abdc, 001d4fe5-73f5-4bae-b126-1f787ea0104e, 002ab28b-e0b9-464a-89fb-12552512a5d0

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