0

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.

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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']);
}

1 Comment

thanks, but its return undefined nama_field. When i try dump $data, its return: array(2) { [0]=> array(3) { ["panjang"]=> string(3) "200" ["tipe_data"]=> string(4) "text" ["nama_field"]=> string(12) "nama lengkap" } [1]=> array(3) { ["panjang"]=> string(3) "201" ["tipe_data"]=> string(6) "number" ["nama_field"]=> string(11) "tahun lahir" } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.