Skip to content

Instantly share code, notes, and snippets.

@mixxorz
Created March 10, 2015 11:17
Show Gist options
  • Save mixxorz/691b107fdbb7b15dd899 to your computer and use it in GitHub Desktop.
Save mixxorz/691b107fdbb7b15dd899 to your computer and use it in GitHub Desktop.
PHP Arrays to JSON
<?php
// This is how you would declare arrays in PHP (version 5.4+)
$someArray = [
"first value",
"second value"
];
// PHP Arrays are apparently also hash maps/dictionaries/whatever
$person = [
"firstName" => "Mitchel",
"lastName" => "Cabuloy"
];
echo $person["firstName"] . "\n";
echo $person["lastName"] . "\n";
// Let's add my age
$person["age"] = 21;
echo $person["age"] . "\n";
// Let's remove my age
unset($person["age"]);
// Let's do the questions example
$firstQuestion = [
"header" => "The Best Header",
"questions" => [
"The Best Question",
"The Second Best Question"
]
];
// Let's add this to an array
$questions = [];
$questions[] = $firstQuestion;
// Let's add another question. Note the syntax $question[] = $newObject;
$questions[] = [
"header" => "Header Two",
"questions" => [
"Foo Question",
"Bar Question"
]
];
// Here, I'm just printing it out.
foreach ($questions as $value) {
echo $value["header"]."\n";
foreach ($value["questions"] as $key => $value) {
echo "[".$key."] ".$value."\n";
}
}
// We can convert this array into JSON really easily!
$questionsInJsonFormat = json_encode($questions);
echo "Here's the JSON string\n";
echo $questionsInJsonFormat;
// This will make your life easier because you can create an array of questions, then convert it to JSON in just one line.
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment