How would you get the JSON data object from two different Arrays in PHP?
Step ①: Two arrays with or without key, value pairs.
Step ②: Assign them to new variables like below or you could directly use them.
Step ③: Now you could write like below to get the JSON object.
Say there are two arrays with key, value pairs, but we need a JSON data object with the first array as keys and the second array as values. Assume these two arrays are posted to PHP file from the browser or from another source. So, how would do you like to do that!
It is very simple, follow the given steps and/or pseudo code and go through the sample script.
Step ①: Two arrays with or without key, value pairs.
$array1 = ( 'one', 'two', 'three', 'four' );
or
$array1 = ( 0 => 'one', 1 => 'two', 2 => 'three', 3 => 'four' );
and
$array2 = ( 'USA', 'CANADA', 'INDIA', 'CHINA' );
or
$array2 = ( 0 => 'USA', 1 => 'CANADA', 2 => 'INDIA', 3 => 'CHINA' );
Step ②: Assign them to new variables like below or you could directly use them.
$mKeys = $array1;
and
$mValues = $array2;
Step ③: Now you could write like below to get the JSON object.
$mJsonValues = array();
foreach ( $pKeys as $mIndex => $mKey )
{
$mJsonValues[ $mKey ] = $mValues[ $mIndex ];
}
$mJsonValues = \json_encode( $mJsonValues );
So, finally $mJsonValues variable contains JSON data with first array values as 'keys' and second array values as 'values'.
You could even write a function for that to do more efficiently. The usage of the script is as follows:
Happy Coding! /**
* Returns an JSON encoded key => val array
*
* @param array $mKeys
* @param array $mValues
* @return string JSON Obj
*/
function getJsonValues( $mKeys, $mValues )
{
/* Check $mKeys */
if ( !$mKeys || !\is_array( $mKeys ) || \count( $mKeys ) < 1 )
{
return null;
}
/* Check $mValues */
if ( !$mValues || !\is_array( $mValues ) || \count( $mValues ) != \count( $mKeys ) )
{
return null;
}
$mJsonValues = array();
foreach ( $mKeys as $mIndex => $mKey )
{
$mJsonValues[ $mKey ] = $mValues[ $mIndex ];
}
return \json_encode( $mJsonValues );
}
/* Usage */
$mJsonValues = getJsonValues( $mKeys, $mValues );

0 Comments