看看这段代码:
$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不能这样工作)
看看这段代码:
$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不能这样工作)
当前回答
array_push($GET, $GET['one']=1);
这对我很管用。
其他回答
$arr = array("key1"=>"value1", "key2"=>"value");
print_r($arr);
/指纹阵列望远镜(key1”= >“value1”、“key2 = >“value2]
有点晚了,但如果你不介意嵌套数组,你可以采用这种方法:
$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"}]
2023
有很多答案。有些有用,有些不错,但有些尴尬。因为你不需要复杂而昂贵的算术运算,循环等简单的操作,如添加一个元素到数组,这里是我的一行添加到数组的函数集合。
$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
)
*/
在99%的情况下,我使用版本1。($array['c'] = 789;)但我喜欢版本4。这是带有splat操作符的版本(https://www.php.net/manual/en/migration56.new-features.php)。
这是可能对你有用的解
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');
当你倾倒的时候。结果是这样的
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)
佩卡就是这么说的…
或者,你也可以像这样使用array_merge:
array_merge($_GET, array($rule[0] => $rule[1]));
但我更喜欢Pekka的方法,因为它更简单。