I have json data stored in database with field name "field_form" like this:
[
{
"panjang": "200",
"tipe_data": "text",
"nama_field": "nama lengkap"
},
{
"panjang": "201",
"tipe_data": "number",
"nama_field": "tahun lahir"
}
]
I need to get "nama_field" data in PHP CodeIgniter controller, when i get the data with code:
$data_form = $this->perizinan_model->get_sub_field_form($id_jenis_izin)->result();
foreach($data_form as $data_field){
var_dump(json_decode($data_field->field_form));
}
var_dump result is
array(2) { [0]=> object(stdClass)#21 (3) { ["panjang"]=> string(3) "200" ["tipe_data"]=> string(4) "text" ["nama_field"]=> string(12) "nama lengkap" } [1]=> object(stdClass)#23 (3) { ["panjang"]=> string(3) "201" ["tipe_data"]=> string(6) "number" ["nama_field"]=> string(11) "tahun lahir" } }
But, i just want to get nama_field data, and store it on array. Thanks before.
CodePudding user response:
From your data structure. It is object inside array then this is the code.
$nama_fields = [];
foreach($data_form as $data_field){
$jsonData = json_decode($data_field->field_form);
if (is_array($jsonData)) {
foreach ($jsonData as $index => $item) {
if (isset($item->nama_field)) {
$nama_fields[] = $item->nama_field;
}
}
}
}
// then use $nama_fields variable.
var_dump($nama_fields);
CodePudding user response:
You have to json_decode
the JSON object and convert it to an associative array.
foreach($data_form as $data_field){
$data = json_decode($data_field->field_form, true);
// the you can access your data as an array
var_dump($data['nama_field']);
}