简体   繁体   English

在php数组的开头插入值

[英]insert value at the beginning of an array in php

my array is 我的数组是

$hello= array( Code => 'TIR', Description => 'Tires', Price => 100 )

now i want to add a value in array beginning of an array not the end of an array.... and results i want is 现在我想在数组的开头而不是数组的末尾添加一个值。...而我想要的结果是

$hello= array( ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )

UPDATE 更新

actually i need any value that is coming will be added in the beginning of an array....this is not single value.. ref=world.... this is coming from output...like if i add quantity=50, then it should be added beginning of an array before 'ref' an array should be 实际上我需要将要出现的任何值都将添加到数组的开头....这不是单个值.. ref = world ....这是来自输出...就像我添加数量= 50 ,则应在“ ref”为数组之前将其添加到数组的开头

$hello= array(quantity=>'50', ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )

I would use array_merge() 我会用array_merge()

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. 将一个或多个数组的元素合并在一起,以便将一个数组的值附加到上一个数组的末尾。 It returns the resulting array. 它返回结果数组。

$hello = array ("Code" => "Tir" .....); // you should really put quotes 
                                        // around the keys!
$world = array ("ref" => "World");

$merged = array_merge($world, $hello);

You can use the + operator: 您可以使用+运算符:

$hello = array( 'Code' => 'TIR', 'Description' => 'Tires', 'Price' => 100 );
$hello = array('ref' => 'World') + $hello;
print_r($hello);

would give 会给

Array
(
    [ref] => World
    [Code] => TIR
    [Description] => Tires
    [Price] => 100
)

Like Pekka said, you should put quotes around the keys. 就像Pekka所说的那样,您应该在密钥周围加上引号。 The PHP manual explicitly states omitting quotes is wrong usage . PHP手册明确指出,省略引号是错误的用法 You might also want to check out my answer about the difference between using the + operator vs using array_merge to decide which you want to use. 您可能还想查看我的答案,以了解使用+运算符与使用array_merge来决定要使用哪个之间的区别

$a= array( 'a' => 'a' );
$b = array( 'b' => 'b' );

$res = $b + $a;
//result: ( 'b' => 'b', 'a' => 'a' )

$ hello = array_merge(array('ref'=>'World'),$ hello);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM