简体   繁体   English

PHP:添加到数组中的数组

[英]Php: add to array within array

Hey I am building JSON from array. 嘿,我正在从数组构建JSON。 It looks something like this: 看起来像这样:

  $jsonkk = array('fields' => [array(
  'x' => 107,
  'y' => 772,
  'width' => 204,
  'height' => 17,
  'page_number' => 0
  )]
  );

Now I would like to add another array into 'fields'so the result would look like this: 现在,我想向“字段”中添加另一个数组,因此结果将如下所示:

array('fields' => [array(
'x' => 107,
'y' => 772,
'width' => 204,
'height' => 17,
'page_number' => 0
),
(
'x' => 646,
'page_number' => 1
)]
);

How to add such arrays inside other arrays? 如何在其他数组中添加这样的数组?

Answers above and another way is; 以上的答案是另一种方法;

 array_push($jsonkk['fields'], array('x'=>646, 'page_number' => 1));

or 要么

 $jsonkk['fields'][] = array('x'=>456, 'page_number' => 1));

or to put in another array inside $jsonkk 或放入$ jsonkk内的另一个数组

 $jsonkk[] = array('x'=>456, 'page_number' => 1));
$jsonk['fields'][] = array("x" => 646, "page_number" => 1);
 $jsonkk['fields'][] = ['x'=>646, 'page_number'=>1]

You could create another array with the fields key, then add them recursively. 您可以使用fields键创建另一个array ,然后以递归方式添加它们。 Follow this link, i think it will help you. 点击此链接,我认为它将为您提供帮助。 enter link description here 在此处输入链接说明

$jsonkk = array(
    'fields' => array(
        array(
          'x' => 107,
          'y' => 772,
          'width' => 204,
          'height' => 17,
          'page_number' => 0
        )
     )
  );

$jsonkk_new = array(
    'fields' => array(
        array(
          'x' => 646,
          'page_number' => 1
        )
     )
  );

  $result = array_merge_recursive($jsonkk, $jsonkk_new);
  print_r($result);

I have no idea what your notation means, doesnt look a var dump... 我不知道您的表示法是什么意思,看上去不是var dump ...

Anyway. 无论如何。 There is no mistery to JSON, it just serializes data. JSON毫无疑问,它只是对数据进行序列化。 Buikd your data whatever way you want, then convert to json with json_encode. 随心所欲地添加数据,然后使用json_encode转换为json。

Now. 现在。 If you dont know basic PHP datasets and how ro work with multidimensional arrays in it, that is another question :p 如果您不了解基本的PHP数据集以及ro如何处理多维数组,那是另一个问题:p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM