Hi,
I am trying to find the best ways to output custom JSON data based on the the array that is passed in. I cannot just use json_encode as there are specific rules that it will not service.
In the passed-in $data $key / $values pairs, if the $values is an array it needs to run the same method as the original passed-in $data.
Here is a example convert_array_to_js( $data ) method that needs to process each inner array:
private function convert_array_to_js( $data, $parenthsis = false ) {
$js ='';
$count = count( $data );
$i = 1;
foreach( $data as $key => $value ) {
if ( true == $parenthsis ) {
$js .= $this->newlines( 1 ) . '{';
} else if ( '{' === $value ) {
$js .= $this->newlines( 1 ) . '{';
} else if ( is_bool( $value ) ) {
$js .= $this->newlines( 2 ) . "'$key': " . json_encode( $value );
$js .= $this->get_comma( $count, $i, $js );
} else if ( '[' == $value ) {
$js .= '[';
} else if ( is_int( $value ) ) {
$js .= $this->newlines( 2 ) . "'$key': " . $value;
$js .= $this->get_comma( $count, $i, $js );
} else if ( ']' == $value ) {
$js .= $value;
$js .= $this->get_comma( $count, $i, $js );
} else if ( $count == $i && true == $parenthsis ) {
$js .= $this->newlines( 1 ) . '}';
} else if ( '}' === $value ) {
$js .= $this->newlines( 1 ) . '}';
} else {
$js .= $this->newlines( 2 ) . "'$key': " . "'$value'";
$js .= $this->get_comma( $count, $i, $js );
}
$i++;
}
return $js;
}
Here is an example arbitrary array:
$values = array(
'foods' =>
array(
'['
, '{'
, array (
'name' => 'carrot'
, 'type' => 'veggie'
, 'goodies' => array(
'chocolate' => array( 'bars', 'cake', 'beans' )
, 'fruits' => array( 'apples', 'pears', 'blue-berries' )
)
)
, '}'
, ']'
)
);
Now I tried using array_walk_recursive() calling itself; however it does not run the callback on $values that are arrays, so this wonāt work.
I also thought about using the SPL iterator classes to define custom behaviour. I have not worked with these very much so I was able to put together a version that flattened the entire array, but this is not what I want.
Output this should define a JS object literal like so:
'foods': [
{
{ 'name' : 'carrot', 'type' : 'veggie' }
, 'goodies' : {
'chocolate': { 'bars', 'cake', 'beans' }
'fruits': { 'apples', 'pears', 'blue-berries' }
}
}
];
If I have a simpler array like:
$data = array(
'data' => '{'
, array{ 'name' => 'weather', 'temp'' => 'cool' }
, array{ 'name' => 'vehicle', 'type' => 'truck' }
, '}'
);
It should output:
'data' : {
{ 'name' : 'weather', 'temp' : 'cool' }
, { 'name' : 'vehicle', 'type' : ; 'truck' }
}
Do you have any recommendations on the best way to do this from the perspective: fast execution, ease of code understanding ( for team members ), and minimizes the foreach depths like array_map and array_walk_recursive do?
Thanks,
Steve