Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-数组中的变量显示为数组_Php_Arrays - Fatal编程技术网

PHP-数组中的变量显示为数组

PHP-数组中的变量显示为数组,php,arrays,Php,Arrays,我有一个向API提交值的数组。如果我手动添加值,它将提交没有问题,但是如果我在数组中添加一个变量,它似乎将值视为数组 这项工作: $post = array( 'email' => 'john@example.com', 'first_name' => 'John', ); 这不起作用: $totals = "'first_name' => 'John', 'email' => 'jo

我有一个向API提交值的数组。如果我手动添加值,它将提交没有问题,但是如果我在数组中添加一个变量,它似乎将值视为数组

这项工作:

$post = array(

    'email'                    => 'john@example.com',
    'first_name'               => 'John',

);
这不起作用:

$totals = "'first_name' => 'John', 'email' => 'john@example.com'",

$post = array(

    $totals

);
API的错误响应为:

[0] => 'first_name' => 'John', 'email' => 'john@example.com',
是否应该有其他方法将我的值添加到API的数组中?

试试这个

$totals = array();
$totals['first_name'] = 'John';
$totals['email'] = 'john@example.com';

$post = $totals;
print_r($post);

为什么下面的方法不起作用

$totals = "'first_name' => 'John', 'email' => 'john@example.com'"
通过在值周围放置双引号
,您将为
$totals
分配一个字符串,并期望它创建一个数组

有几个选项可以解决它。选项一

$post['first_name'] = 'John';
$post['email'] = 'john@example.com';
另一种选择:

$post = array('first_name' => 'John', 'email' => 'john@example.com');
$totals = array('first_name' => 'John', 'email' => 'john@example.com');
$post = $totals;
还有另一个选择:

$post = array('first_name' => 'John', 'email' => 'john@example.com');
$totals = array('first_name' => 'John', 'email' => 'john@example.com');
$post = $totals;

由于我不确定
$totals
值来自何处,因此可能有更多的选项。

您基本上是试图从字符串创建一个数组,这是直接不可能的

$totals = "'first_name' => 'John', 'email' => 'john@example.com'";
它将创建一个值为的字符串 '名字'=>'约翰','电子邮件'=>'john@example.com"

现在你的陈述

$post = array($totals);

基本上是将该字符串分配给索引为零的$post数组。

第一个示例是一个带有两个键的数组(
email
first\u name
):

您的第二个示例与此相同:

$post = array(
    0 => "'first_name' => 'John', 'email' => 'john@example.com'"
);
它只包含一个条目,在键
0
处。它的值看起来像PHP代码(但不是)。它肯定与第一个示例不同

显然,您的问题是如何在PHP中处理数组

阅读。文档页面解释了如何使用。PHP还提供了很多

阅读文档后,您将能够以多种方式构建和修改阵列。例如:

$post = array();
$post['email'] = 'john@example.com';
$post['first_name'] = 'John';

你需要用方括号把关键部分包起来,这样就行了

$totals = "['first_name'] => 'John', ['email'] => 'john@example.com'";

$post = array($totals);

print_r($post);