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

前端 未结 13 1659
余生分开走
余生分开走 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:21

    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,
      ...
    )
    

提交回复
热议问题