Re: json_encode confusion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 10 November 2011 14:45, Bastien Koert <phpster@xxxxxxxxx> wrote:
> Morning all,
>
> I've been having some fun with converting a text data file import into
> a json object for storage.
>
> I have a text file that is pipe delimited coming in via an upload. The
> first row is the headers and the second row is the data.
>
> Using this code:
>
> $data = file("inline_Nov_8_2011.txt");
>
> if(count($data)==2){
>
>        $keys   = explode("|", $data[0]);
>        $fields = explode("|", $data[1]);
>
>        $combine = array_combine($keys, $fields);
>
>        $json = json_encode($combine);
> }
>
> After the combine, I get an array that looks like this
>
> Array
> (
>    ['Legal Last Name '] => Andros
>    ['Legal Middle Initial '] =>
>    ['Legal First Name '] => Marisa
>    ['Maiden/Other Name '] =>
>    ['Social Insurance No. '] => 123456789
>    ['Date of Birth '] => 2/1/1988
>    ['Gender '] => Female
> )
>
> But the json encoded value looks like this (there are way more
> elements but this should be enough to represent what I need to do).
>
> {null:"Andros",null:"",null:"Marisa",null:"",null:"123456789",null:"2\/1\/1988",null:"Female"}
>
> I have been googling for info about allowed values for the json keys,
> but can't seem to find a clear doc on what is allowed and what isn't.
> I have tried unquoted keys, replaced the spaced with underscores but
> nothing I do seems to help.
>
> When I echo out the json encoded data, the keys are all nulls.
>
> Can someone point me in the correct direction? It may be that I need
> to manually create the key names as an array first, which I was hoping
> to avoid since the file format coming from the client is still in some
> flux.

<?php
$data = array(
   'Legal Last Name ' => 'Andros',
   'Legal Middle Initial ' => '',
   'Legal First Name ' => 'Marisa',
   'Maiden/Other Name ' => '',
   'Social Insurance No. ' => 123456789,
   'Date of Birth ' => '2/1/1988',
   'Gender ' => 'Female'
);

echo json_encode($data, JSON_FORCE_OBJECT);
?>

outputs ...

{"Legal Last Name ":"Andros","Legal Middle Initial ":"","Legal First
Name ":"Marisa","Maiden\/Other Name ":"","Social Insurance No.
":123456789,"Date of Birth ":"2\/1\/1988","Gender ":"Female"}


-- 
Richard Quadling
Twitter : EE : Zend : PHPDoc : Fantasy Shopper
@RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY : bit.ly/lFnVea :
fan.sh/6/370

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux