For a JSON array like this...

[
  {"number":1,"value":"foo"},
  {"number":2,"value":"bar"},
  {"number":1,"value":"fubar"}
]

...I want to detect the fact that not all "numbers" are unique. (No, I cannot change the JSON syntax.) I came up with this method, which seems to work, but just wondered if anyone sees a cleaner, hopefully more efficient way?

    /**
     * Determine if a questions json object has duplicate question numbers
     * @param string $json
     * @return bool  true: at least one dup, false: good to go
     * @throws FException
     */
	protected function duplicateQuestion($json)
    {
        $data = json_decode($json, true);
        if($data === null) {
            throw new FException(500, "Invalid JSON string");
        }
        $keys = array();
        foreach($data as $answer) {
            $keys[$answer['number']] = 1;
        }
        return count($data) != count($keys);
    }
        protected function duplicateQuestion($json) 
        { 
            $data = json_decode($json, true); 
            if($data === null) { 
                throw new FException(500, "Invalid JSON string"); 
            } 
    
        return count(array_flip(array_column($data, 'number'))) != count($data);
    }  
    

    Probably performs roughly the same though...

      Nice. 🙂 My testing suggests my version is just a tiny bit faster (and I mean tiny), so I think I'll just stick with it for now as a workable solution. But I learned about array_column() today.

        Write a Reply...