简体   繁体   中英

Problem in use of json_encode?

I insert data with json_encode() in database, now i want get( select * from <table> ... ) only name_unitsin of database? i want output this-> salam & mokhles & fadat

In database row units :

[{"name_units":"salam","price_units":"74,554","checkbox_units":["minibar","mobleman"]},
 {"name_units":"mokhles","price_units":"4,851,269","checkbox_units":["mobleman","tv"]},
 {"name_units":"fadat","price_units":"85,642","checkbox_units":["minibar","mobleman","tv"]}]

.

$query_hotel_search = $this->db->query("SELECT * FROM hotel_submits WHERE name LIKE '%$hotel_search%' ORDER BY name asc");
$data = array();
foreach ($query_hotel_search->result() as $row)
{
   $units = json_decode($row->units);
   $data[] = array('name' => $row->name, 'units' =>$units['name_units']); // Line 24
}
echo json_encode($data);

This is output above code:

A PHP Error was encountered
Severity: Notice
Message: Undefined index: name_units
Line Number: 24

[{"name":"Jack","units":null}]

You're getting an array of stdClass objects as a result from json_decode , rather than an associative array as you'd expect. It looks like you've got an array of JSON strings located in the same cell of your DB.

Assuming that's how your DB table is structure, if you want to output

salam & mokhles & fadat

then try this:

foreach( $query_hotel_search->result() as $row ) {
    $units = json_decode( $row->units );
    $names = '';
    foreach( $units as $unit ) {
        $names .= "{$unit->name_units} & ";
    }
}
echo substr( $names, 0, -2 );

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