【问题标题】:populate input fields with JSON Object value使用 JSON 对象值填充输入字段
【发布时间】:2014-03-24 17:41:40
【问题描述】:

首先,抱歉,无论如何我都不是 php 专家,我正在为此苦苦挣扎,但我在数据库中有一个 JSON 格式的条目。

然后我试图从这个对象中提取值到一系列输入框中。

使用后:

$response = json_decode($row['responseJSON']);

其中 responseJSON 是我的表的名称,我返回以下对象:

stdClass Object ( [fields] => stdClass Object ( [marketingID] => stdClass Object ( [attributes] => stdClass Object ( [type] => hidden [id] => marketingID [value] => 0 ) [value] => 7 ) [marketingTelephone] => stdClass Object ( [attributes] => stdClass Object ( [type] => text [class] => form-control [id] => marketingTelephone [required] => true [label] => Telephone ) [value] => +44 123 456789 ) [marketingEmail] => stdClass Object ( [attributes] => stdClass Object ( [type] => email [class] => form-control [id] => marketingEmail [required] => true [placeholder] => you@company.com ) [value] => contact@helloworld.com ) ) [files] => stdClass Object ( [marketingLogo] => stdClass Object ( [name] => logo1.png [path] => /resources\logo1.png [size] => 2408 [mime] => [attributes] => stdClass Object ( [id] => marketingLogo [type] => file [label] => Choose File ) ) ) ) 

和输入框:

<perch:input id="marketingLogo" type="file" label="Choose File" />
<perch:input type="text" class="form-control" id="marketingTelephone" required="true"  label="Telephone" />
<perch:input type="email" class="form-control" id="marketingEmail" required="true" placeholder="you@company.com" />

我的问题是,我正在尝试使用以下方式遍历对象:

json_o->marketingID (and various versions) but to no avail.

然后我想,也许我需要沿着以下路线去做:

foreach ($response as $object) {
   {
    foreach ($object as $property=>$value)
      {...

但老实说,这一切都超出了我的想象,因为我只是不太明白我需要如何遍历所有内容才能获得对象中给出的值。

我希望这是有道理的,对于缺乏知识我深表歉意......

【问题讨论】:

    标签: php json forms input


    【解决方案1】:

    如果您将 JSON 解码为数组而不是对象,可能会更容易。这可以通过向 json_decode 提供第二个参数 (true) 来实现:

    $response = json_decode($row['responseJSON'], true);
    

    这应该适用于 foreach 块

    【讨论】:

    • 谢谢,我试过了,但就是不明白如何正确询问 for each 循环以深入了解我想要的值。
    • 事实上你可能根本不需要 foreach 块。您可以访问如下嵌套元素(例如访问 MarketingTelephone 的属性):$response['fields']['marketingTelephone']['attributes']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 2016-04-24
    • 2016-03-25
    相关资源
    最近更新 更多