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

问题描述 投票:291回答:18

看看这段代码:

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

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

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

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

php arrays
18个回答
680
投票

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

你必须使用

$arrayname[indexname] = $value;

3
投票
 $arr = array("key1"=>"value1", "key2"=>"value");
    print_r($arr);

//打印数组['key1'=>“value1”,'key2'=>“value2”]


3
投票

我想知道为什么还没有发布最简单的方法:

$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];

将qzxswpoi和两个数组合并在一起就像是一样


2
投票
array_merge.

这很好用。在数组中创建具有其值的键


2
投票

嗨,我有同样的问题,我找到这个解决方案你应该使用两个数组然后将它们两者结合

array_push($arr, ['key1' => $value1, 'key2' => value2]);

参考: <?php $fname=array("Peter","Ben","Joe"); $age=array("35","37","43"); $c=array_combine($fname,$age); print_r($c); ?>


1
投票

简单的方法:

w3schools

$GET = array(); $key = 'one=1'; parse_str($key, $GET);


1
投票

array_push($ GET,$ GET ['one'] = 1);

适合我


1
投票

示例array_merge()....

http://php.net/manual/de/function.parse-str.php

数组([color] =>绿色,[0] => 2,[1] => 4,[2] => a,[3] => b,[形状] =>梯形,[4] => 4 )


0
投票

添加到$array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result);key的第一个位置

value

0
投票

我写了一个简单的函数:

$newAarray = [newIndexname => newIndexValue] ;

$yourArray = $newAarray + $yourArray ;

这样我就可以轻松地“插入”新元素:

function push(&$arr,$new) {
    $arr = array_merge($arr,$new);
}

66
投票

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

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

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

// key already known
$array[$key] = $value;

56
投票

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

<?php

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

print_r($arr3);

// prints:
// array(
//   'foo' => 'bar',
//   'baz' => 'bof',
// );

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

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


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);

希望这会对某人有所帮助


17
投票

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

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

array_merge($_GET, array($rule[0] => $rule[1]));

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


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 ....呵呵我建议你只使用这个概念用于我的意图。任何其他方法都可能存在安全风险。在那里,做了我的免责声明!


7
投票

这是对你有用的解决方案

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');

When you dump it. The result like this

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)

4
投票

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

$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));

为了澄清,如果输出的json_encode($ main_array)看起来像[{“Key”:“10”}]


4
投票

有点奇怪,但这对我有用

    $array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
    $array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
    $array3 = array();

    $count = count($array1);

    for($x = 0; $x < $count; $x++){
       $array3[$array1[$x].$x] = $array2[$x];
    }

    foreach($array3 as $key => $value){
        $output_key = substr($key, 0, -1);
        $output_value = $value;
        echo $output_key.": ".$output_value."<br>";
    }
© www.soinside.com 2019 - 2024. All rights reserved.