Php - 创建json对象

时间:2017-12-11 10:13:45

标签: php json

我正在尝试从Ninja Forms获得的数据创建一个json对象,如下所示:

{
    "title": "Contact Me",
    "fields": [
        { 
            "label": "Name",
            "type": "textbox",
            "required": "1"
        },
        { 
            "label": "Email",
            "type": "email",
            "required": "1"
        }
    ]
}

我想这样做,就像这样:

$settings = ['label', 'type', 'required'];
$formTitle = Ninja_Forms()->form( 1 )->get()->get_setting('title');
$formFields = Ninja_Forms()->form(1)->get_fields();
$data = ['title' => $formTitle];

foreach ($formFields as $formField) {
    $key = $formField->get_setting('key');

    foreach ($settings as $setting) {
        $data['fields'][$key][][$setting] = $formField->get_setting($setting);
    }
}

return $data;

但是,结果如下:

{
    "title": "Contact Me",
    "fields": {
        "name": [
            { "label": "Name" },
            { "type": "textbox" },
            { "required": "1"}
        ],
        "email": [
            { "label": "Email" },
            { "type": "email" },
            { "required": "1" }
        ],

我该怎么做,结果看起来像我上面显示的那个? 我也尝试过这样:

  foreach ($settings as $setting) {
     $data['fields'][] = $formField->get_setting($setting);
  }

但是,这给了我这样的结果:

{
    "title": "Contact Me",
    "fields": [
        "Name",
        "textbox",
        "1",
        "Email",
        "email",
        "1",
        "Message",
        "textarea",
        "1",
        "Submit",
        "submit",
        null
    ]
}

2 个答案:

答案 0 :(得分:0)

这给了我想要的结果:

foreach ($formFields as $formField) {
  $key = $formField->get_setting('key');

  foreach ($settings as $setting) {
    $object[$setting]  = $formField->get_setting($setting);
  }
  $data['fields'][] = $object;
}

return $data;

答案 1 :(得分:0)

查看此内容的一种方法是计算数据的维度。以您想要的格式,最深的项目是:

{ "fields": [ { "label": "Name"

所以你有object -> array -> object

如果我们在代码中缩进每个数组,我们有:

$data // outermost array
  ['fields']
    [$key]
       [] // innermost array
          [$setting] = $value; // key in innermost array

或者,如果我们只用一个值声明它:

$data = array(
  'field' => array(
     $key => array(
        0 => array(
           $setting => $value
        )
     )
   )
);

所以你有4个级别的数组,而不是3.

与JSON相比,将带有数字键的数组作为" array"一个非数字键作为"对象",模式为object -> object -> array -> object

所以我们需要消除[$key],因为它会创建额外的object维度。

我们也不想在[]为每个项目增加密钥,所以我们需要提前提出我们的价值......

foreach ($settings as $setting) {
  $object[$setting]  = $formField->get_setting($setting);
}
$data['fields'][] = $object;

...或提前选择我们的密钥:

$i++;
foreach ($settings as $setting) {
    $data['fields'][$i] = $formField->get_setting($setting);
}