I’m very happy that a lot of developers have found my cvLinkSelect class and found it useful. cvLinkSelect is a simple Mootools 1.2 class that links form select elements based on the previous value via JSON requests. The php part was very basic though and a visitor pointed me to write the php part better, shorter and more functional. And here we are, just a simple 10 line php function.

In most cases you’ll get the data from a SQL database or something like that and in therefore it’s an array.

/* $arr = array from the database */
$arr = array(//array(id,name),
			 	array(15,'15 inch'),
				array(17,'17 inch'),
				array(19,'19 inch')
			);

Make sure that the you’ll only get the id and the name or another identifier. The total has to be two otherwise it don’t work.

To get the JSON request in the right format I’ve written a small function that will add the value and html key to the arrays.

/**
* Function to set the key for each value
* Requires: array(array())
* Returns: JSON format for cvLinkSelect class
*/
function json_cvLinkSelect($arr = array()){
	$json = array(); /* temporary array */

	foreach($arr as $ob){ /*walk trough the original array */
		$keys = array('value','html'); /*define the two keys */
		array_push($json,array_combine($keys,$ob)); /* push the new array to the temporary array, $json */
	}

	return json_encode($json); /* return the $json array */
}

The output will be:

[{"value":"hard","html":"Hard"},{"value":"soft","html":"Soft"}]

I’ve updated the zipfile with the working example if you guys need more info.

Enjoy!

Related Posts

Leave a Comment

Get your own Gravatar!
Your email will never be published!

Notify me of followup comments via e-mail

Top of Page