看看这段代码:
$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不能这样工作)
当前回答
我想知道为什么最简单的方法还没有公布:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
其他回答
我想把我的答案补充到表格中,如下:
//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);
希望这能帮助到一些人
将值压入数组会自动为其创建一个数字键。
当向数组添加键-值对时,您已经拥有键,不需要为您创建一个键。将键推入数组是没有意义的。只能设置数组中特定键的值。
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
我通常这样做:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
array_push($GET, $GET['one']=1);
这对我很管用。
这是可能对你有用的解
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)