1

I have an array like this,

Array
    (
        [0] => 1
        [1] => naveen
    )

    Array
    (
        [0] => 2
        [1] => bos
    )

I am using a csv upload to insert data's to the mongodb

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {           
        echo "<pre>";
        print_r($data);         
        echo "</pre>";
}

i want to convert the array into a json format, i have tried the json_encode($data); but it is coming like this

["1","naveen"]

["2","bos"]

What i want to do make this array as json encoded format

2
  • Show us how you're using json_encode. Commented Mar 12, 2014 at 12:46
  • Where i will read the csv file. i have a upload.php there i write the html form and action to a slim function. inside that function i would add the read the csv and inert to mongo db? Commented Mar 13, 2014 at 5:40

2 Answers 2

4

You need to put it all into one array and then json encode it:

$array = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {           
    $array[] = $data;
}
$json = json_encode($array);
Sign up to request clarification or add additional context in comments.

6 Comments

Please spread the word that the reverse json_decode is the usual answer to "how do I write this query in PHP".
Hi John Conde Thankyou for your reply i am getting like this [["1","naveen"]][["1","naveen"],["2","bos"]], is it possible to make the array {"1":"naveen"},{"2":"bos"} like this?
Try casting the arrays to objects: $array[] = (object) $data;
I have tried this some changes but not exact one [{"0":"1","1":"naveen"},{"0":"2","1":"bos"}]
That is how it will look because it is in one array, hence the array syntax around the objects.
|
0

Yes finally make it work.

        $keys="";
        $result=array();
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if($keys==""){
                $keys = $data;
            }else{
                $output = array();          
                for ($i=0; $i <count($keys) ; $i++) { 
                    $output[$keys[$i]]=$data[$i];

                }
                array_push($result, $output);
            }

        }
        echo "<pre>";
        print_r(json_encode($result));
        echo "</pre>";

Got Output Like below

[{"id":"1","name":"naveen"},{"id":"2","name":"bos"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.