[英]array_push into an existing key
So I have been trying to push an array into an array, but it ends up creating it seperately.所以我一直在尝试将一个数组推入一个数组,但它最终会单独创建它。 Not really sure how to phrase it, but below is the php code:
不太确定如何表达,但下面是 php 代码:
function build_embed() {
$output = array(
"username" => "Form Username",
"description" => "Form Description",
"tts" => false,
"embeds" => [
[
"title" => "Form Title",
"type" => "rich",
"fields" => []
]
]
);
foreach ( $this->inputs as $val ) :
$id = $val['id'];
$label = $val['label'];
$newfields = [
"name" => $label,
"value" => $id,
"inline" => false
];
array_push($output['embeds']['fields'], $newfields);
endforeach;
return $output;
}
Output of the array:数组的 Output:
array(4) {
["username"]=> string(13) "Form Username"
["description"]=> string(16) "Form Description"
["tts"]=> bool(false)
["embeds"]=> array(2) {
[0]=> array(3) {
["title"]=> string(10) "Form Title"
["type"]=> string(4) "rich"
["fields"]=> array(0) { }
}
["fields"]=> NULL
}
}
Should be like:应该是这样的:
array(4) {
["username"]=> string(13) "Form Username"
["description"]=> string(16) "Form Description"
["tts"]=> bool(false)
["embeds"]=> array(2) {
[0]=> array(3) {
["title"]=> string(10) "Form Title"
["type"]=> string(4) "rich"
["fields"]=> array("name" => "Test","value" => "Test","inline" => false) { }
}
}
You have defined embeds
as a multidimensional array with one element array ( see the array structure here ), so you would push onto the first element of embeds
which is 0
and then fields
:您已将
embeds
定义为具有一个元素数组的多维数组(请参见此处的数组结构),因此您将推入embeds
的第一个元素,即0
,然后是fields
:
array_push($output['embeds'][0]['fields'], $newfields);
However this is the more common and practical way:然而,这是更常见和实用的方法:
$output['embeds'][0]['fields'][] = $newfields;
If it were defined like this, it would work with the current code:如果它是这样定义的,它将适用于当前代码:
"embeds" => [
"title" => "Form Title",
"type" => "rich",
"fields" => []
]
Or:或者:
$output['embeds']['fields'][] = $newfields;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.