如何将值和键都推送到数组中

Gal*_*Gal 327 php arrays

看看这段代码:

$GET = array();    
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
Run Code Online (Sandbox Code Playgroud)

我正在寻找这样的东西,以便:

print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Run Code Online (Sandbox Code Playgroud)

有这个功能吗?(因为array_push不会这样工作)

Pek*_*ica 709

不,没有array_push()关联数组的等价物,因为无法确定下一个键.

你必须使用

$arrayname[indexname] = $value;
Run Code Online (Sandbox Code Playgroud)

  • 我不明白.这不是将项添加到数组中的常规方法吗? (10认同)
  • @KingGoeks` $ arrayname = array('indexname1'=> $ value1,'indexname2'=> $ value2);`将它们设置为`$ arrayname`中的唯一项目.如果你已经设置了'$ arrayname`并希望保留其值,请尝试`$ arrayname + = $ anotherarray`.请记住,第一个数组中的任何现有键都会被第二个数组覆盖. (6认同)
  • “请记住,第一个数组中的任何现有键都将被第二个覆盖”,这是不正确的,第一个数组具有优先权。如果你做`$a = array("name" => "John"); $a += array("name" => "Tom");`那么 `$a["name"]` 将是 "John" (2认同)

dec*_*eze 71

将值入数组会自动为其创建数字键.

将键值对添加到数组时,您已经拥有该键,您不需要为其创建一个键值.将密钥推入数组是没有意义的.您只能在数组中设置特定键的值.

// no key
array_push($array, $value);
// same as:
$array[] = $value;

// key already known
$array[$key] = $value;
Run Code Online (Sandbox Code Playgroud)


Cha*_*ser 57

您可以使用union运算符(+)来组合数组并保留添加的数组的键.例如:

<?php

$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;

print_r($arr3);

// prints:
// array(
//   'foo' => 'bar',
//   'baz' => 'bof',
// );
Run Code Online (Sandbox Code Playgroud)

所以你可以做到$_GET += array('one' => 1);.

有关union运算符的使用的更多信息与http://php.net/manual/en/function.array-merge.phparray_merge中的文档有关.

  • `array_merge()`和`+`运算符之间的基本区别是当2个数组包含相同键的值时`+`运算符忽略第二个数组的值(不覆盖),也不重新编号/重新索引数值按键... (3认同)

jef*_*fff 19

正是佩卡说的......

或者,如果您需要,可以使用如下所示的array_merge:

array_merge($_GET, array($rule[0] => $rule[1]));
Run Code Online (Sandbox Code Playgroud)

但我更喜欢Pekka的方法,因为它更简单.


Nas*_*sim 19

我想在表格中添加我的答案,这里是:

//connect to db ...etc
$result_product = /*your mysql query here*/ 
$array_product = array(); 
$i = 0;

foreach ($result_product as $row_product)
{
    $array_product [$i]["id"]= $row_product->id;
    $array_product [$i]["name"]= $row_product->name;
    $i++;
}

//you can encode the array to json if you want to send it to an ajax call
$json_product =  json_encode($array_product);
echo($json_product);
Run Code Online (Sandbox Code Playgroud)

希望这会对某人有所帮助


Mai*_*rey 13

2023年

很多答案。有些很有帮助,有些则很好但很尴尬。由于您不需要复杂且昂贵的算术运算、循环等来执行向数组添加元素等简单操作,因此这里是我的One-Liner-Add-To-Array-Functions集合。

$array = ['a' => 123, 'b' => 456]; // init Array

$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.

print_r($array);
// Output:
/* 
Array
(
    [a] => 123
    [b] => 456
    [c] => 789
    [d] => 012
    [e] => 345
    [f] => 678
)
*/
Run Code Online (Sandbox Code Playgroud)

99,99% 我使用版本 1。( $array['c'] = 789;)。但我喜欢第4版。这是带有 splat 运算符的版本(https://www.php.net/manual/en/migration56.new-features.php)。


Far*_*han 8

这是对你有用的解决方案

Class Form {
# Declare the input as property
private $Input = [];

# Then push the array to it
public function addTextField($class,$id){
    $this->Input ['type'][] = 'text';
    $this->Input ['class'][] = $class;
    $this->Input ['id'][] = $id;
}

}

$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');
Run Code Online (Sandbox Code Playgroud)

当你转储它.结果是这样的

array (size=3)
  'type' => 
    array (size=3)
      0 => string 'text' (length=4)
      1 => string 'text' (length=4)
      2 => string 'text' (length=4)
  'class' => 
    array (size=3)
      0 => string 'myclass1' (length=8)
      1 => string 'myclass2' (length=8)
      2 => string 'myclass3' (length=8)
  'id' => 
    array (size=3)
      0 => string 'myid1' (length=5)
      1 => string 'myid2' (length=5)
      2 => string 'myid3' (length=5)
Run Code Online (Sandbox Code Playgroud)


Cor*_*ers 7

我只是在寻找同样的事情,我意识到,再一次,我的想法是不同的,因为我老了.我一直回到BASIC和PERL,有时候我忘记了PHP中的实际问题.

我刚刚使用此功能从数据库获取所有设置,它们是3列.setkey,item(key)&value(value)并使用相同的键/值将它们放入一个名为settings的数组中,而不像上面那样使用push.

非常简单和简单


// Get All Settings
$settings=getGlobalSettings();


// Apply User Theme Choice
$theme_choice = $settings['theme'];

.. etc etc etc ....




function getGlobalSettings(){

    $dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
    mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
    $MySQL = "SELECT * FROM systemSettings";
    $result = mysqli_query($dbc, $MySQL);
    while($row = mysqli_fetch_array($result)) 
        {
        $settings[$row['item']] = $row['value'];   // NO NEED FOR PUSH
        }
    mysqli_close($dbc);
return $settings;
}


所以像其他帖子一样解释...在php中,当你使用时不需要"推"一个数组

Key => Value

AND ...也没有必要先定义数组.

$阵列=阵列();

不需要定义或推送.只需分配$ array [$ key] = $ value; 它同时自动推送和声明.

我必须补充一点,出于安全原因,(P)oor(H)elpless(P)rotection,我的意思是编程为傻瓜,我的意思是PHP ....呵呵我建议你只使用这个概念我想要的.任何其他方法都可能存在安全风险.在那里,做了我的免责声明!


小智 5

有点晚了,但如果你不介意嵌套数组,你可以采用这种方法:

$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
Run Code Online (Sandbox Code Playgroud)

澄清一下,如果你输出json_encode($main_array)看起来像[{"Key":"10"}]


Ale*_*Vay 5

我想知道为什么尚未发布最简单的方法:

$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
Run Code Online (Sandbox Code Playgroud)

就像将两个数组与合并一样array_merge

  • 传奇!!只是 `$arr += [$key =&gt; $value];` 对我来说非常好,谢谢! (3认同)
  • 不完全一样,在array_merge中,右边的数组在key冲突时获胜,在“+=”中左边的数组获胜 (2认同)
  • 如果两个数组具有相同的键,则 `array_merge` 和 *array union* (`+=`) 的行为相反,即 array_merge 将尊重第二个数组中的值,而数组 union 将尊重第一个数组中的值。 (2认同)