array: store multiple values per key

后端 未结 3 1883
心在旅途
心在旅途 2021-01-19 10:47

I once trying adding two values with the same key, but it didn\'t work. It overrode the old value. Isn\'t it possible to add more than one value with the same key, and when

3条回答
  •  自闭症患者
    2021-01-19 11:07

    You can create a wrapper function:

    function add_to_array($array, $key, $value) {
        if(array_key_exists($key, $array)) {
            if(is_array($array[$key])) {
                $array[$key][] = $value;
            }
            else {
                $array[$key] = array($array[$key], $value);           
            }
        }
        else {
            $array[$key] = array($value);
        }
    }
    

    So you just create a 2-dimensional array. You can retrieve the "linked list" (another array) by normal array access $array[$key].

    Whether this approach is convenient is up to you.

提交回复
热议问题