Categories
PHP Tutorials

Formatting Multidimensional Array in PHP

Every PHP programmer or definitively all programmers must have encountered array in respective programming languages they’re good at. Either it single or multidimensional, every array is tricky.

If you are a wordpress developer either it’s plugin or theme or simply administrator, you must have known the popular Contact Form 7 and the independent plugin associated along with it, Contact Form 7 to Database. These are two popular plugins in WordPress SVN with multi-million download hits. What Contact Form 7 does is capturing the information and save it in database before Contact Form 7 sent the email and the database design is not somewhat beginners friendly. It uses the Unix formatted timestamp as secondary key to identify the group of columns which the information belongs to.

Now, if you query the table using WPDB global class, you get those in same format as below:

Array
(
    [0] => stdClass Object
        (
            [entry_id] => 6
            [entry_time] => 1369643273
            [entry_key] => last_name
            [entry_value] => Smith
        )

    [1] => stdClass Object
        (
            [entry_id] => 5
            [entry_time] => 1369643273
            [entry_key] => first_name
            [entry_value] => John
        )

    [2] => stdClass Object
        (
            [entry_id] => 7
            [entry_time] => 1369643273
            [entry_key] => age
            [entry_value] => 26
        )

    [3] => stdClass Object
        (
            [entry_id] => 8
            [entry_time] => 1369643273
            [entry_key] => ethnicity
            [entry_value] => Caucasian
        )

    [4] => stdClass Object
        (
            [entry_id] => 9
            [entry_time] => 1369643451
            [entry_key] => first_name
            [entry_value] => Fredirick
        )

    [5] => stdClass Object
        (
            [entry_id] => 10
            [entry_time] => 1369643451
            [entry_key] => last_name
            [entry_value] => Scheidner
        )

    [6] => stdClass Object
        (
            [entry_id] => 11
            [entry_time] => 1369643451
            [entry_key] => age
            [entry_value] => 29
        )

    [7] => stdClass Object
        (
            [entry_id] => 12
            [entry_time] => 1369643451
            [entry_key] => ethnicity
            [entry_value] => European
        )

)

It’s in a form of multidimensional array. Now if you analyze the array above, you can see that these information belong to a single table entry and the entry ID is not supposedly use as information key instead just a unique key that every database required to hold unique values. Only three array key that is useful: entry_time, entry_key and entry_value. The entry_time as I’ve explain earlier is a UNIX formatted time that was stored at the time the user submit the form using either PHP strtotime or MySql NOW().

So how we format this multidimensional array into array that represent the proper information like below?

Array
(
    [1369643451] => Array
        (
            [first_name] => Fredirick
            [last_name] => Scheidner
            [age] => 29
            [ethnicity] => European
        )

)

That’s our tutorial this time. Formatting multidimensional array in PHP using same values as key. Before we start let’s take a look one more time on this reformatted array. This only good on fetching single record but how about if we’re going to fetch more than one and how we arrange those records?

Array
(
    [0] => Array
        (
            [1369643451] => Array
                (
                    [first_name] => Fredirick
                    [last_name] => Scheidner
                    [age] => 29
                    [ethnicity] => European
                )

        )

    [1] => Array
        (
            [1369643273] => Array
                (
                    [last_name] => Smith
                    [first_name] => John
                    [age] => 26
                    [ethnicity] => Caucasian
                )

        )

)

Above is what our final output will look like. We are going to create PHP function that reformat multidimensional PHP array and use the repetitive values ( in our case, entry_time ) as array key. First, create a function and named it reconstruct that accepts 4 instances: the unformatted array, array key to be used, the actual array key from unformatted array and the array values.

function reconstruct( $arrayToReconstruct, $basedKey, $entry_key, $entry_value )
{

}

Create an empty array that will hold the formatted array and we will return it in final output.

$reconstructedArray = array();

Next, determine each array key and corresponding value, then check if that key exist in array key to be used.

if( in_array( $basedKey, $arrayToReconstruct[$key] ) )
{

}

After that, create an array that output as our sample above.

$reconstructedArray[$basedKey][ $arrayToReconstruct[$key][$entry_key] ]=$arrayToReconstruct[$key][$entry_value];

And finally return the reformatted array.

return $reconstructedArray;

Our final function will be look like this:

function reconstruct( $arrayToReconstruct, $basedKey, $entry_key, $entry_value ){

		$reconstructedArray = array();

		foreach( $arrayToReconstruct as $key=>$value ){
			if( in_array( $basedKey, $arrayToReconstruct[$key] ) ){

				$reconstructedArray[$basedKey][ $arrayToReconstruct[$key][$entry_key] ]=$arrayToReconstruct[$key][$entry_value];

			}
		}
		return $reconstructedArray;

	}

It’s that simple. So how do we use this function? First determine what array key that we will use from unformatted array we have which are ” 1369643451” for Fredirick Scheidner and “1369643273” for John Smith. Then use this function while looping the array key.

$key = array( "1369643451", "1369643273" );
$new = array();

foreach( $key as $value ){
	$new[] = reconstruct( $data, $value , "entry_key", "entry_value" );
}

That’s it, that’s how simple it is in formatting multidimensional array in PHP. I hope you can learn from this.