我使用多数组输入字段在CakePHP 3项目的HTML中存储数据
<input name="media[0]['text']">
<input name="media[0]['color']" ?>
<input name="media[1]['text']" ?>
<input name="media[1]['color']"?>
and so on...
使用PHP通过JSON编码媒体数组将输入字段值存储到数据库
$column_field = json_encode($this->request->getData('media'));
存储在数据库JSON字符串中,如
[{"'text'":"example text 1","'color'":"#ff00ff"},{"'text'":"example text 2","'color'":"#00ff99"}]
当我需要数据时我解码字符串以转换回php数组
$data = (array)json_decode($column_field);
在debug($data)
上,它给出了
[
(int) 0 => object(stdClass) {
'text' => 'example text 1'
'color' => '#ff00ff'
},
(int) 1 => object(stdClass) {
'text' => 'example text 2'
'color' => '#00ff99'
}
]
然后我遍历每个数组元素
foreach($data as $item) {
debug($item->text);
}
但它返回null。
将数组对象更改为数组
foreach ($data as $item) {
$item = (array)$item;
debug($item);
}
给出
[
''text'' => 'example text 1',
''color'' => '#ff00ff',
]
这可以通过$item["'text'"]
如何正确解析它以$item['text']
或$item->text
访问它?
答案 0 :(得分:2)
def form_valid(self, form):)
country_pk = self.request.POST["country"]
state_pk = self.request.POST["state"]
district_pk = self.request.POST["district"]
country = Country.objects.get(pk = country_pk)
#--- district
#---- state
#if you have defined a str method you can just proceed as
#as below since the render will call __str__ else
#you can use country.name, state.name, district.name
msg = "You belong to {country}, {state}, {district}. Me too.
;)".format(country=country, state=state, district=district)
如果您确实需要将字段命名为“media [0] ['text']”,则可以<input name="media[0][text]">
instead of
<input name="media[0]['text']">