How to add an array value to the middle of an associative array?

前端 未结 13 1634
余生分开走
余生分开走 2020-12-08 00:36

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<

13条回答
  •  太阳男子
    2020-12-08 01:29

    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.

提交回复
热议问题