mattkirwan
11/22/2013 - 7:27 PM

Nice little snippet to generate a customisable 'choice' array (up to 5 elements can be displayed) from an array of items - perfect for drop

Nice little snippet to generate a customisable 'choice' array (up to 5 elements can be displayed) from an array of items - perfect for drop downs/checkboxes and such.

<?php

/***********************************************
Raw Data:

@$raw_data

Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => Matt
            [surname] => Kirwan
            [account_id] => 1
        )

    [1] => Array
        (
            [id] => 2
            [firstname] => Joe
            [surname] => Bloggs
            [account_id] => 2
        )

)
***********************************************/

$primary_column = 'id';
$display_columns = array('id', 'firstname', 'surname');
$display_format = '%d: %s - %s';

list($d1, $d2, $d3, $d4, $d5) = array_pad($display_columns, 5, '');

foreach(new \RecursiveArrayIterator($raw_data) as $item)
{
	$returned_array[$item[$primary_column]] = sprintf($display_format,
		$item[$d1],
		$item[$d2],
		$item[$d3],
		$item[$d4],
		$item[$d5]);
}

$returned_array = $returned_array
		
/***********************************************
Outputs:

Array
(
    [1] => 1: Matt - Kirwan
    [2] => 2: Joe - Bloggs
)
************************************************/