0

Here is a my PHP array. I want to convert it into JSON. after a converting to JSON. than after I want to save it in database how can I achieve this?

Array
(
    [0] => 6:30pm
    [1] => 
)
Array
(
    [0] => 8:00pm
    [1] => 
)
2

3 Answers 3

3

json_encode() - Returns the JSON representation of a value.

Returns a string containing the JSON representation of value.

A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:

Example One:

<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar,JSON_FORCE_OBJECT); 
?>

Output:

{"0":"apple","1":"orange","2":"banana","3":"strawberry"} 

Example Two:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

Output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

After you need to fetch the data you need json_decode() and it follows as this.

json_decode() — Decodes a JSON string

Takes a JSON encoded string and converts it into a PHP variable.

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Example:

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>

Output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you really need to store json in the database, you can use json_encode and json_decode.

3 Comments

Why wouldn't he store json in database? It was always OK but now has even more sense: dev.mysql.com/doc/refman/5.7/en/json.html
you kidding, ain't you?
@jakubwrona why would i be kidding?
0

use this the json_encode($array) and it will gives you a json string,than you can save it to a row.

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.