How to add an array value to the middle of an asso

2019-01-21 13:45发布

Lets say I have this array:

$array = array('a'=>1,'z'=>2,'d'=>4);

Later in the script, I want to add the value 'c'=>3 before 'z'. How can I do this?

EDIT: Yes, the order is important. When I run a foreach() through the array, I do NOT want this newly added value added to the end of the array. I am getting this array from a mysql_fetch_assoc()

EDIT 2: The keys I used above are placeholders. Using ksort() will not achieve what I want.

EDIT 3: http://www.php.net/manual/en/function.array-splice.php#88896 accomplishes what I'm looking for but I'm looking for something simpler.

EDIT 4: Thanks for the downvotes. I gave feedback to your answers and you couldn't help, so you downvoted and requested to close the question because you didn't know the answer. Thanks.

EDIT 5: Take a sample db table with about 30 columns. I get this data using mysql_fetch_assoc(). In this new array, after column 'pizza' and 'drink', I want to add a new column 'full_dinner' that combines the values of 'pizza' and 'drink' so that when I run a foreach() on the said array, 'full_dinner' comes directly after 'drink'

12条回答
混吃等死
2楼-- · 2019-01-21 14:40

According to your original question the best answer I can find is this:

$a = array('a'=>1,'z'=>2,'d'=>4);

$splitIndex = array_search('z', array_keys($a));
$b = array_merge(
        array_slice($a, 0, $splitIndex), 
        array('c' => 3), 
        array_slice($a, $splitIndex)
);

var_dump($b);
array(4) {
  ["a"]=>
  int(1)
  ["c"]=>
  int(3)
  ["z"]=>
  int(2)
  ["d"]=>
  int(4)
}

Depending on how big your arrays are you will duplicate quite some data in internal memory, regardless if you use this solution or another.

Furthermore your fifth edit seems to indicate that alternatively your SQL query could be improved. What you seem to want to do there would be something like this:

SELECT a, b, CONCAT(a, ' ', b) AS ab FROM ... WHERE ...

If changing your SELECT statement could make the PHP solution redundant, you should definitely go with the modified SQL.

查看更多
再贱就再见
3楼-- · 2019-01-21 14:41

Try this

$array['c']=3;

An associative array is not ordered by default, but if you wanted to sort them alphabetically you could use ksort() to sort the array by it's key.

If you check out the PHP article for ksort() you will se it's easy to sort an array by its key, for example:

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

// The above example will output:
a = orange
b = banana
c = apple
d = lemon
查看更多
\"骚年 ilove
4楼-- · 2019-01-21 14:43

Associative arrays are not ordered, so you can simply add with $array['c'] = 3.

If order is important, one option is switch to a data structure more like:

$array = array(
   array('a' => 1),
   array('b' => 2)
   array('d' => 4)
);

Then, use array_splice($array, 2, 0, array('c' => 3)) to insert at position 2. See manual on array_splice.

查看更多
地球回转人心会变
5楼-- · 2019-01-21 14:46

you can add it by doing

$array['c']=3;

and if you absolutely want it sorted for printing purposes, you can use php's ksort($array) function

if the keys are not sortable by ksort, then you will have to create your own sort by using php's uasort function. see examples here

http://php.net/manual/en/function.uasort.php

查看更多
神经病院院长
6楼-- · 2019-01-21 14:49
function insertValue($oldArray, $newKey, $newValue, $followingKey) {

    $newArray = array ();
    foreach (array_keys($oldArray) as $k) {
        if ($k == $followingKey)
            $newArray[$newKey] = $newValue;
        $newArray[$k] = $oldArray [$k];
    }

    return $newArray;
}

You call it as

insertValue($array, 'c', '3', 'z')

As for Edit 5:

edit your sql, so that it reads

SELECT ..., pizza, drink, pizza+drink as full_meal, ... FROM ....

and you have the column automatically:

Array (
  ...
  'pizza' => 12,
  'drink' => 5,
  'full_meal' => 17,
  ...
)
查看更多
Deceive 欺骗
7楼-- · 2019-01-21 14:51
function putarrayelement(&$array, $arrayobject, $elementposition, $value = null) {

        $count = 0;
        $return = array();
        foreach ($array as $k => $v) {
        if ($count == $elementposition) {
                if (!$value) {
                    $value = $count;
                }
            $return[$value] = $arrayobject;
            $inserted = true;
        }
        $return[$k] = $v;
        $count++;
        }
        if (!$value) {
           $value = $count;
        }
        if (!$inserted){
            $return[$value];
        }
        $array = $return;
       return $array;
     }

        $array = array('a' => 1, 'z' => 2, 'd' => 4);
        putarrayelement($array, '3', 1, 'c');
        print_r($array);
查看更多
登录 后发表回答