1

I'm using multi-array input field to store data in HTML of CakePHP 3 project

<input name="media[0]['text']">
<input name="media[0]['color']" ?>
<input name="media[1]['text']" ?>
<input name="media[1]['color']"?>

and so on...

Using PHP to store the input field value to database by JSON encoding media array

$column_field = json_encode($this->request->getData('media'));

which stores in database JSON string like

[{"'text'":"example text 1","'color'":"#ff00ff"},{"'text'":"example text 2","'color'":"#00ff99"}]

again when I need the data I decode the string to convert back to php array

$data = (array)json_decode($column_field);

on debug($data), it gives

[
        (int) 0 => object(stdClass) {
                'text' => 'example text 1'
                'color' => '#ff00ff'
        },
        (int) 1 => object(stdClass) {
                'text' => 'example text 2'
                'color' => '#00ff99'
        }
]

then I loop through each array element

foreach($data as $item) {
   debug($item->text);
}

But it returns null.

changing array object to array

foreach ($data as $item) {
  $item = (array)$item;
  debug($item);
}

gives

[
        ''text'' => 'example text 1',
        ''color'' => '#ff00ff',
]

and this is accessed by $item["'text'"]

How to parse it properly to access it either $item['text'] or $item->text?

1 Answer 1

2
<input name="media[0][text]">
instead of
<input name="media[0]['text']">

If you really need to name your field "media[0]['text']" you can access it by $item->{'text'}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I want the first one <input name="media[0][text]">

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.