Меню Рубрики

Php json encode windows 1251

json_encode и кириллица

Мальчишки, девчонки, низкий всем поклон! Больше отдыхайте и всё будет отлично!

У меня не работает пишет ошибку:

Notice: Use of undefined constant JSON_UNESCAPED_UNICODE — assumed ‘JSON_UNESCAPED_UNICODE’ in /var/www/support/MySQL_Datatables/process.php on line 8

Warning: json_encode() expects parameter 2 to be long

эм… я на 99,999 уверен, что у меня utf-8.
на всякий случай перед помещением в массив конвертил так:
iconv(‘cp1251’, ‘utf-8’, ‘значение’);
Действительно, null превратился в последовательность типа u0437u0430 и тд.

То есть снова не могу декодировать. Ещё одна проблема в том, что между encode и decode весь JSON сохраняется в БД и декодируется уже оттуда.

Чувствую, что истина где-то рядом, но туплю 🙁

Или изначально работайте c utf-8, но тогда вам скорее всего придется все скрипты переписать (потому что обычные строковые функции уже не подойдут), или заранее конвертируйте данные.

$ar = array(«name»=>’значение’);
$json=json_encode($ar);
mysql_connect(«localhost», «qwer», «qwer»);
mysql_select_db(«termito»);
mysql_query(‘set names utf8’);
$q=sprintf(«INSERT INTO `cin`(`info`) VALUES(‘%s’)», $json);
echo $q;
mysql_query($q);

mysql_connect(«localhost», «qwer», «qwer»);
mysql_select_db(«termito»);
mysql_query(‘set names utf8’);
$r = mysql_query(«select * from `company_info` WHERE `id`=».mysql_insert_id());
$r = mysql_fetch_array($r);
$a = json_decode($r[‘info’],true);
echo(($a[‘name’]));

/*на выходе упорно u0437u043du0430u0447u0435u043du0438u0435*/

Источник

json_encode

(PHP 5 >= 5.2.0, PHP 7, PECL json >= 1.2.0)

json_encode — Возвращает JSON-представление данных

Описание

Возвращает строку, содержащую JSON-представление для указанного value .

На кодирование влияет параметр options и, кроме того, кодирование значений типа float зависит от значения serialize_precision.

Список параметров

value — значение, которое будет закодировано. Может быть любого типа, кроме resource.

Функция работает только с кодировкой UTF-8.

PHP реализует надмножество JSON, который описан в первоначальном » RFC 7159.

Битовая маска, составляемая из значений JSON_FORCE_OBJECT , JSON_HEX_QUOT , JSON_HEX_TAG , JSON_HEX_AMP , JSON_HEX_APOS , JSON_INVALID_UTF8_IGNORE , JSON_INVALID_UTF8_SUBSTITUTE , JSON_NUMERIC_CHECK , JSON_PARTIAL_OUTPUT_ON_ERROR , JSON_PRESERVE_ZERO_FRACTION , JSON_PRETTY_PRINT , JSON_UNESCAPED_LINE_TERMINATORS , JSON_UNESCAPED_SLASHES , JSON_UNESCAPED_UNICODE , JSON_THROW_ON_ERROR . Смысл этих констант объясняется на странице JSON констант.

Устанавливает максимальную глубину. Должен быть больше нуля.

Возвращаемые значения

Возвращает строку ( string ), закодированную JSON или FALSE в случае возникновения ошибки.

Список изменений

Версия Описание
7.3.0 Добавлена константа JSON_THROW_ON_ERROR для параметра options .
7.2.0 Добавлены константы JSON_INVALID_UTF8_IGNORE и JSON_INVALID_UTF8_SUBSTITUTE для параметра options .
7.1.0 Добавлена константа JSON_UNESCAPED_LINE_TERMINATORS для параметра options .
7.1.0 При кодировании чисел с плавающей запятой используется serialize_precision вместо precision.

Примеры

Пример #1 Пример использования json_encode()

= array( ‘a’ => 1 , ‘b’ => 2 , ‘c’ => 3 , ‘d’ => 4 , ‘e’ => 5 );

echo json_encode ( $arr );
?>

Результат выполнения данного примера:

Пример #2 Пример использования json_encode() с опциями

echo «Обычно: » , json_encode ( $a ), «\n» ;
echo «Теги: » , json_encode ( $a , JSON_HEX_TAG ), «\n» ;
echo «Апострофы: » , json_encode ( $a , JSON_HEX_APOS ), «\n» ;
echo «Кавычки: » , json_encode ( $a , JSON_HEX_QUOT ), «\n» ;
echo «Амперсанды: » , json_encode ( $a , JSON_HEX_AMP ), «\n» ;
echo «Юникод: » , json_encode ( $a , JSON_UNESCAPED_UNICODE ), «\n» ;
echo «Все: » , json_encode ( $a , JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE ), «\n\n» ;

echo «Отображение пустого массива как массива: » , json_encode ( $b ), «\n» ;
echo «Отображение неассоциативного массива как объекта: » , json_encode ( $b , JSON_FORCE_OBJECT ), «\n\n» ;

$c = array(array( 1 , 2 , 3 ));

echo «Отображение неассоциативного массива как массива: » , json_encode ( $c ), «\n» ;
echo «Отображение неассоциативного массива как объекта: » , json_encode ( $c , JSON_FORCE_OBJECT ), «\n\n» ;

$d = array( ‘foo’ => ‘bar’ , ‘baz’ => ‘long’ );

echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d ), «\n» ;
echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d , JSON_FORCE_OBJECT ), «\n\n» ;
?>

Результат выполнения данного примера:

Пример #3 Пример использования опции JSON_NUMERIC_CHECK

Результатом выполнения данного примера будет что-то подобное:

Пример #4 Пример с последовательными индексами, начинающимися с нуля, и непоследовательными индексами массивов

echo «Последовательный массив» . PHP_EOL ;
$sequential = array( «foo» , «bar» , «baz» , «blong» );
var_dump (
$sequential ,
json_encode ( $sequential )
);

echo PHP_EOL . «Непоследовательный массив» . PHP_EOL ;
$nonsequential = array( 1 => «foo» , 2 => «bar» , 3 => «baz» , 4 => «blong» );
var_dump (
$nonsequential ,
json_encode ( $nonsequential )
);

echo PHP_EOL . «Последовательный массив с одним удаленным индексом» . PHP_EOL ;
unset( $sequential [ 1 ]);
var_dump (
$sequential ,
json_encode ( $sequential )
);
?>

Результат выполнения данного примера:

Пример #5 Пример использования опции JSON_PRESERVE_ZERO_FRACTION

Результат выполнения данного примера:

Примечания

В случае ошибки кодирования можно использовать json_last_error() для определения точной ошибки.

При кодировании массива в случае, если его индексы не являются последовательными числами от нуля, то все индексы кодируются в строковые ключи для каждой пары индекс-значение.

Как и эталонный кодировщик JSON, json_encode() будет создавать JSON в виде простого значения (то есть не объект и не массив), если ему переданы типы string , integer , float или boolean в качестве входящего значения value . Большинство декодеров воспринимают эти значения как правильный JSON, но некоторые нет, потому что спецификация неоднозначна на этот счет.

Всегда проверяйте, что ваш декодер JSON может правильно обрабатывать данные, которые вы создаете с помощью json_encode() .

Смотрите также

  • JsonSerializable
  • json_decode() — Декодирует строку JSON
  • json_last_error() — Возвращает последнюю ошибку
  • serialize() — Генерирует пригодное для хранения представление переменной

User Contributed Notes 37 notes

This isn’t mentioned in the documentation for either PHP or jQuery, but if you’re passing JSON data to a javascript program, make sure your program begins with:

Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?

Just watch this usecase:

// International phone number
json_encode (array( ‘phone_number’ => ‘+33123456789’ ), JSON_NUMERIC_CHECK );
?>

And then you get this JSON:

Maybe it makes sense for PHP (as is_numeric(‘+33123456789’) returns true), but really, casting it as an int?!

So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!

A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.

= Array( ‘isa’ , ‘dalawa’ , ‘tatlo’ );
var_dump ( $myarray );
/* output
array(3) <
[0]=>
string(3) «isa»
[1]=>
string(6) «dalawa»
[2]=>
string(5) «tatlo»
>
*/
?>

As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array.

= Array( ‘isa’ , ‘dalawa’ , ‘tatlo’ );

unset( $myarray [ 1 ]);
var_dump ( $myarray );
/* output
array(2) <
[0]=>
string(3) «isa»
[2]=>
string(5) «tatlo»
>
*/
?>

Unsetting an element will also remove the keys. json_encode() will now assume that this is an object, and will encode it as such.

SOLUTION: Use array_values() to re-index the array.

This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed under GNU/AGPLv3 or GPLv3 like you prefer):

function json_readable_encode ( $in , $indent = 0 , $from_array = false )
<
$_myself = __FUNCTION__ ;
$_escape = function ( $str )
<
return preg_replace ( «!([\b\t\n\r\f\»\\’])!» , «\\\\\\1» , $str );
>;

foreach ( $in as $key => $value )
<
$out .= str_repeat ( «\t» , $indent + 1 );
$out .= «\»» . $_escape ((string) $key ). «\»: » ;

if ( is_object ( $value ) || is_array ( $value ))
<
$out .= «\n» ;
$out .= $_myself ( $value , $indent + 1 );
>
elseif ( is_bool ( $value ))
<
$out .= $value ? ‘true’ : ‘false’ ;
>
elseif ( is_null ( $value ))
<
$out .= ‘null’ ;
>
elseif ( is_string ( $value ))
<
$out .= «\»» . $_escape ( $value ) . «\»» ;
>
else
<
$out .= $value ;
>

if (!empty( $out ))
<
$out = substr ( $out , 0 , — 2 );
>

$out = str_repeat ( «\t» , $indent ) . » <\n" . $out ;
$out .= «\n» . str_repeat ( «\t» , $indent ) . «>» ;

For PHP5.3 users who want to emulate JSON_UNESCAPED_UNICODE, there is simple way to do it:
function my_json_encode ( $arr )
<
//convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being «hidden» from normal json_encoding
array_walk_recursive ( $arr , function (& $item , $key ) < if ( is_string ( $item )) $item = mb_encode_numericentity ( $item , array ( 0x80 , 0xffff , 0 , 0xffff ), 'UTF-8' ); >);
return mb_decode_numericentity ( json_encode ( $arr ), array ( 0x80 , 0xffff , 0 , 0xffff ), ‘UTF-8’ );

I came across the «bug» where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.

You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.

// Pretend we already have a complex SimpleXML object stored in $xml
$json = json_encode (new SimpleXMLElement ( $xml -> asXML (), LIBXML_NOCDATA ));
?>

A note about json_encode automatically quoting numbers:

It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:

We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.

This can lead to problems within javascript functions expecting the values to be numeric.

This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.

The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.

If you need to force an object (ex: empty array) you can also do:

( (object) $arr ); ?>

which acts the same as

Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.

Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.

In a Latin-1 encoded file, write this:
= array( ‘é’ , 1 );
var_dump ( json_encode ( $a ));
?>

PHP = 5.5:
bool(false)

PHP 5.5 has it right of course (if encoding fails, return false) but its likely to introduce errors when updating to 5.5 because previously you could get the rest of the JSON even when one string was not in UTF8 (if this string wasn’t used, you’d never notify it’s nulled)

// CREATES AN ARRAY OF SimpleXMLElement OBJECTS
$obj = SimpleXML_Load_String ( $xml );
var_dump ( $obj );
echo PHP_EOL ;

// SHOW THE ATTRIBUTES HIDDEN IN THE SimpleXMLElement OBJECTS
foreach ( $obj as $sub )
<
echo PHP_EOL . (string) $sub -> quantity . ‘ ‘ . (string) $sub -> quantity [ ‘type’ ];
>
echo PHP_EOL ;

// USING THE OBJECT, CREATE A JSON STRING
$jso = json_encode ( $obj );
echo htmlentities ( $jso ); // ‘type’ IS LOST
echo PHP_EOL ;

Solution for UTF-8 Special Chars.

If you are planning on using this function to serve a json file, it’s important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add «;» to the end.

It took me a while to figure this out so I thought I’d save others the aggravation.

( ‘Content-Type: text/javascript; charset=utf8’ );
header ( ‘Access-Control-Allow-Origin: http://www.example.com/’ );
header ( ‘Access-Control-Max-Age: 3628800’ );
header ( ‘Access-Control-Allow-Methods: GET, POST, PUT, DELETE’ );

$file = ‘rss.xml’ ;
$arr = simplexml_load_file ( $file ); //this creates an object from the xml file
$json = ‘(‘ . json_encode ( $arr ). ‘);’ ; //must wrap in parens and end with semicolon
print_r ( $_GET [ ‘callback’ ]. $json ); //callback is prepended for json-p
?>

WARNING! Do not pass associative arrays if the order is important to you. It seems that while FireFox does keep the same order, both Chrome and IE sort it. Here’s a little workaround:

= array();
$arWrapper [ ‘k’ ] = array_keys ( $arChoices );
$arWrapper [ ‘v’ ] = array_values ( $arChoices );
$json = json_encode ( $arWrapper );
?>

This function has weird behavior regarding error reporting in PHP version 5.4 or lower. This kind of warning is raised only if you configure PHP with «display_errors=Off» (!?): «PHP Warning: json_encode(): Invalid UTF-8 sequence in argument . «

You can reproduce this behavior:
// Warning not displayed, not logged
ini_set ( ‘display_errors’ , ‘1’ );
json_encode ( urldecode ( ‘bad utf string %C4_’ ));

// Warning not displayed but logged
ini_set ( ‘display_errors’ , ‘0’ );
json_encode ( urldecode ( ‘bad utf string %C4_’ ));
?>

This is considered feature — not-a-bug — by PHP devs:
https://bugs.php.net/bug.php?id=52397
https://bugs.php.net/bug.php?id=63004

If you need pretty-printed output, but want it indented by 2 spaces instead of 4:

$json_indented_by_4 = json_encode($output, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
$json_indented_by_2 = preg_replace(‘/^( +?)\\1(?=[^ ])/m’, ‘$1’, $json_indented_by_4);

Note, string keys have to be UTF-8 also! (So array_walk_recursive() isn’t good way)

Consider this solution for fixing invalid UTF-8:

//$a=array(‘zażółć gęślą jaźń ZAŻÓŁĆ GĘŚLĄ JAŹŃ’, ‘Paiçao’=>3, 4=>array(‘€€=>5, ‘€’, 6));
$a =array( urldecode ( ‘za%BF%F3%B3%E6+g%EA%9Cl%B9+ja%9F%F1+ZA%AF%D3%A3%C6+G%CA%8CL%A5+JA%8F%D1’ ), urldecode ( ‘Pai%E7ao’ )=> 3 , 4 =>array( ‘€€’ => 5 , ‘€’ , 6 )); // (for better example, independent of .php file charset)

// Normal test
echo json_encode ( $a , JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES );
// Kind of error depends on PHP version.
// false or ‘<"0":null,null:3,"4":>’

if (! function_exists ( ‘urlencode_recurs’ )) <
function urlencode_recurs (& $arr ) <
foreach ( $arr as $key => & $val ) <
if ( is_array ( $val )) <
urlencode_recurs ( $val );
$newarr [( is_string ( $key ) ? urlencode ( $key ) : $key )] = $val ; // Not $arr[. ] = . to preserve keys/elements order
> else <
$newarr [( is_string ( $key ) ? urlencode ( $key ) : $key )] = ( is_string ( $val ) ? urlencode ( $val ) : $val ); // Not $arr[. ] = . to preserve keys/elements order
//if (is_string($key)) unset($arr[$key]); // Not this, to preserve keys/elements order, as above
>
>
$arr = $newarr ;
> >

if ( is_array ( $a )) urlencode_recurs ( $a );

// Fixed test
echo urldecode ( json_encode ( $a , JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES ));
// ‘<"0":"zażółć gęślą jaźń ZAŻÓŁĆ GĘŚLĄ JAŹŃ","Paiçao":3,"4":<"€€":5,"0":"€","1":6>>’
?>

json_encode will encode array as object if the array;s keys are not sequential starting with zero

$b = [1=>’a’, 2=>’b’, 3=>[0 => ‘aa’, 1 => ‘c’, 2 => ‘dd’]];
var_dump(jsoon_encode($b)); //

i would expect PHP to follow the original structure or at least add a parameter to do so

( 0 );
ini_set ( ‘display_errors’ , FALSE );

$file = __DIR__ . ‘/utf8.csv’ ;

function csvtojson ( $inputFile , $delimiter )
<

if (( $handleFile = fopen ( $inputFile , ‘r’ )) == false ) <
throw new Exception ( «Não foi possível abrir o arquivo para importar: ‘ $file ‘» );
>

while (( $data = fgetcsv ( $handleFile , 4000 , $delimiter )) !== false ) <
$data = array_map ( ‘trim’ , $data );

if (! isset( $keys )) <
$keys = array_map ( ‘trim’ , $data );
continue;
>

$dados [] = array_combine ( $keys , $data );

$result = json_encode ( $dados , JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT );
echo $result ;

$arquivo = «data_» . date ( ‘ymdhis’ ). «.json» ;
$fp = fopen ( $arquivo , «a+» );
fwrite ( $fp , $result );

fclose ( $handleFile );
fclose ( $fp );

$jsonresult = csvtojson ( $file , «;» );

= fopen ( ‘php://stdin’ , ‘r’ );
$json = @ json_encode (array( ‘a’ => ‘foo’ , ‘b’ => $fp ));
var_dump ( $json );

In my application, I had objects that modeled database rows with a few one to many relationships, so one object may have an array of other objects.

I wanted to make the object properties private and use getters and setters, but I needed them to be serializable to json without losing the private variables. (I wanted to promote good coding practices but I needed the properties on the client side.) Because of this, I needed to encode not only the normal private properties but also properties that were arrays of other model objects. I looked for awhile with no luck, so I coded my own:

You can place these methods in each of your classes, or put them in a base class, as I’ve done. (But note that for this to work, the children classes must declare their properties as protected so the parent class has access)

abstract class Model <

public function toArray () <
return $this -> processArray ( get_object_vars ( $this ));
>

private function processArray ( $array ) <
foreach( $array as $key => $value ) <
if ( is_object ( $value )) <
$array [ $key ] = $value -> toArray ();
>
if ( is_array ( $value )) <
$array [ $key ] = $this -> processArray ( $value );
>
>
// If the property isn’t an object or array, leave it untouched
return $array ;
>

public function __toString () <
return json_encode ( $this -> toArray ());
>

>
?>

Externally, you can just call

echo $theObject ;
//or
echo json_encode ( $theObject -> toArray ());
?>

And you’ll get the json for that object. Hope this helps someone!

// alternative json_encode
function _json_encode ( $val )
<
if ( is_string ( $val )) return ‘»‘ . addslashes ( $val ). ‘»‘ ;
if ( is_numeric ( $val )) return $val ;
if ( $val === null ) return ‘null’ ;
if ( $val === true ) return ‘true’ ;
if ( $val === false ) return ‘false’ ;

$assoc = false ;
$i = 0 ;
foreach ( $val as $k => $v ) <
if ( $k !== $i ++) <
$assoc = true ;
break;
>
>
$res = array();
foreach ( $val as $k => $v ) <
$v = _json_encode ( $v );
if ( $assoc ) <
$k = ‘»‘ . addslashes ( $k ). ‘»‘ ;
$v = $k . ‘:’ . $v ;
>
$res [] = $v ;
>
$res = implode ( ‘,’ , $res );
return ( $assoc )? ‘<' . $res . '>‘ : ‘[‘ . $res . ‘]’ ;
>

This function is more accurate and faster than, for example, that one:
http://www.php.net/manual/ru/function.json-encode.php#89908
(RU: эта функция работает более точно и быстрее, чем указанная выше).

Here’s a quick function to pretty-print some JSON. Optimizations welcome, as this was a 10-minute dealie without efficiency in mind:

// Pretty print some JSON
function json_format ( $json )
<
$tab = » » ;
$new_json = «» ;
$indent_level = 0 ;
$in_string = false ;

$json_obj = json_decode ( $json );

if( $json_obj === false )
return false ;

$json = json_encode ( $json_obj );
$len = strlen ( $json );

for( $c = 0 ; $c $len ; $c ++)
<
$char = $json [ $c ];
switch( $char )
<
case ‘ <' :
case ‘[‘ :
if(! $in_string )
<
$new_json .= $char . «\n» . str_repeat ( $tab , $indent_level + 1 );
$indent_level ++;
>
else
<
$new_json .= $char ;
>
break;
case ‘>’ :
case ‘]’ :
if(! $in_string )
<
$indent_level —;
$new_json .= «\n» . str_repeat ( $tab , $indent_level ) . $char ;
>
else
<
$new_json .= $char ;
>
break;
case ‘,’ :
if(! $in_string )
<
$new_json .= «,\n» . str_repeat ( $tab , $indent_level );
>
else
<
$new_json .= $char ;
>
break;
case ‘:’ :
if(! $in_string )
<
$new_json .= «: » ;
>
else
<
$new_json .= $char ;
>
break;
case ‘»‘ :
if( $c > 0 && $json [ $c — 1 ] != ‘\\’ )
<
$in_string = ! $in_string ;
>
default:
$new_json .= $char ;
break;
>
>

Be careful with floating values in some locales (e.g. russian) with comma («,») as decimal point. Code:

Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like «LC_NUMERIC, ‘en_US.utf8′» before using json_encode.

Please note that there was an (as of yet) undocumented change to the json_encode() function between 2 versions of PHP with respect to JSON_PRETTY_PRINT:

In version 5.4.21 and earlier, an empty array [] using JSON_PRETTY_PRINT would be rendered as 3 lines, with the 2nd one an empty (indented) line, i.e.:
«data»: [

In version 5.4.34 and above, an empty array [] using JSON_PRETTY_PRINT would be rendered as exactly [] at the spot where it occurs, i.e.
«data: [],

This is not mentioned anywhere in the PHP changelist and migration documentations; neither on the json_encode documentation page.

This is very useful to know when you are parsing the JSON using regular expressions to manually insert portions of data, as is the case with my current use-case (working with JSON exports of over several gigabytes requires sub-operations and insertion of data).

For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn’t want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.

Note that, because javascript converts JSON data into either nested named objects OR vector arrays, it’s quite difficult to represent mixed PHP arrays (arrays with both numerical and associative indexes) well in JSON. This function does something funky if you pass it a mixed array — see the comments for details.

I don’t make a claim that this function is by any means complete (for example, it doesn’t handle objects) so if you have any improvements, go for it.

/**
* Converts an associative array of arbitrary depth and dimension into JSON representation.
*
* NOTE: If you pass in a mixed associative and vector array, it will prefix each numerical
* key with «key_». For example array(«foo», «bar» => «baz») will be translated into
* <"key_0": "foo", "bar": "baz">but array(«foo», «bar») would be translated into [ «foo», «bar» ].
*
* @param $array The array to convert.
* @return mixed The resulting JSON string, or false if the argument was not an array.
* @author Andy Rusterholz
*/
function array_to_json ( $array )<

if( ! is_array ( $array ) ) <
return false ;
>

$associative = count ( array_diff ( array_keys ( $array ), array_keys ( array_keys ( $array )) ));
if( $associative )<

$construct = array();
foreach( $array as $key => $value )<

// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.

// Format the key:
if( is_numeric ( $key ) ) <
$key = «key_ $key » ;
>
$key = ‘»‘ . addslashes ( $key ). ‘»‘ ;

// Format the value:
if( is_array ( $value )) <
$value = array_to_json ( $value );
> else if( ! is_numeric ( $value ) || is_string ( $value ) ) <
$value = ‘»‘ . addslashes ( $value ). ‘»‘ ;
>

// Add to staging array:
$construct [] = » $key : $value » ;
>

// Then we collapse the staging array into the JSON form:
$result = «< " . implode ( ", " , $construct ) . " >» ;

$construct = array();
foreach( $array as $value )<

// Format the value:
if( is_array ( $value )) <
$value = array_to_json ( $value );
> else if( ! is_numeric ( $value ) || is_string ( $value ) ) <
$value = ‘»‘ . addslashes ( $value ). ‘»‘ ;
>

// Add to staging array:
$construct [] = $value ;
>

// Then we collapse the staging array into the JSON form:
$result = «[ » . implode ( «, » , $construct ) . » ]» ;
>

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Php installer windows msi
  • Php installer windows installer
  • Php header charset windows 1251
  • Php exec без ожидания ответа windows
  • Php default charset windows 1251