如何将值和键都推送到 PHP 数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2121548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to push both value and key into PHP array
提问by Gal
Take a look at this code:
看看这段代码:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
我正在寻找这样的东西:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_pushwon't work this way)
有没有一个功能可以做到这一点?(因为array_push不会这样工作)
回答by Pekka
Nope, there is no array_push()equivalent for associative arrays because there is no way determine the next key.
不,array_push()关联数组没有等效项,因为无法确定下一个键。
You'll have to use
你必须使用
$arrayname[indexname] = $value;
回答by deceze
Pushinga value into an array automatically creates a numeric key for it.
将值推入数组会自动为其创建一个数字键。
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
将键值对添加到数组时,您已经拥有键,不需要为您创建键。将键推入数组没有意义。您只能设置数组中特定键的值。
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
回答by Charlie Schliesser
You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:
您可以使用联合运算符 ( +) 来组合数组并保留添加数组的键。例如:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);.
所以你可以这样做$_GET += array('one' => 1);。
There's more info on the usage of the union operator vs array_mergein the documentation at http://php.net/manual/en/function.array-merge.php.
array_merge在http://php.net/manual/en/function.array-merge.php的文档中有更多关于联合运算符使用的信息。
回答by Nassim
I would like to add my answer to the table and here it is :
我想将我的答案添加到表格中,这里是:
//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);
hope that this will help somebody
希望这会帮助某人
回答by jeffff
Exactly what Pekka said...
正是佩卡所说的……
Alternatively, you can probably use array_merge like this if you wanted:
或者,如果您愿意,您可以像这样使用 array_merge:
array_merge($_GET, array($rule[0] => $rule[1]));
But I'd prefer Pekka's method probably as it is much simpler.
但我可能更喜欢 Pekka 的方法,因为它更简单。
回答by AlexioVay
I wonder why the simplest method hasn't been posted yet:
我想知道为什么最简单的方法还没有发布:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
回答by Faris Rayhan
This is the solution that may useful for u
这是可能对你有用的解决方案
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)
回答by Cory Cullers
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
我只是在寻找同样的东西,我意识到,我的想法再次不同,因为我是老派。我一路回到 BASIC 和 PERL,有时我忘记了 PHP 中的事情真的很简单。
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
我刚刚制作了这个函数来从数据库中获取所有设置,其中它们是 3 列。setkey, item (key) & value (value) 并使用相同的键/值将它们放入名为 settings 的数组中,而不像上面那样使用 push 。
Pretty easy & simple really
真的很简单很简单
// 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;
}
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
所以就像其他帖子解释的那样......在php中,当你使用时不需要“推”一个数组
Key => Value
键 => 值
AND... There is no need to define the array first either.
AND... 也不需要先定义数组。
$array=array();
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
不需要定义或推送。只需分配 $array[$key] = $value; 它自动同时是推送和声明。
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
我必须补充一点,出于安全原因,(P)oor (H)elpless (P)rotection,我的意思是为傻瓜编程,我的意思是 PHP……呵呵,我建议你只将这个概念用于我的意图。任何其他方法都可能存在安全风险。在那里,做出我的免责声明!
回答by Mesh Manuel
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine. creates the the key with its value in the array
这工作得很好。使用数组中的值创建键
回答by Bjorn Lottering
A bit weird, but this worked for me
有点奇怪,但这对我有用
$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>";
}

