Anuj TBE
Anuj TBE

Reputation: 9790

parsing php multi array input field

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?

Upvotes: 1

Views: 53

Answers (1)

Philipp Gebert
Philipp Gebert

Reputation: 131

<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'}

Upvotes: 2

Related Questions