I’m printing a <ul> of array $_SESSION['words'] in PHP.
// PHP print new words as links
echo '<ul id="wordlist">';
foreach($_SESSION['words'] as $word => $description) {
echo '<li id="wordlist"><a href="#">' . $word . '</a></li>';
}
The array is simple – words are stored as keys and the descriptions for words will be values, e.g.
array(5) { ["word1"]=> int(1) ["word2"]=> int(2) ["word3"]=> int(3) ["word4"]=> int(4) ["word5"]=> int(5) }
I plan to manipulate items in the array by selecting a $word and adding a $description and adding it to the array, so I’m thinking I’ll use jQuery to do it.
My question is: if I create a JSON array from this PHP array, can I print it out in the same way and manipulate it? I encoded it with $myJSON = json_encode($_SESSION['words']); but I’m already stuck attempting to print out the keys/values from the JSON! Thanks…
You description indicates to me that you are not using JSON in any way, other than to use PHP’s JSON encoding function. It sounds like you are encoding your PHP associative array into a JSON string and then writing that string into your HTML output. If this is the case, then your JSON is really a JavaScript object.
So let’s assume your resulting markup is this:
Notice that my id attribute values are unique. You used the same id attribute value multiple times; that is invalid markup. Also, I kept the markup in each list element simple for this example (just text).
So, given this markup, we could write the following JavaScript:
In this JavaScript, I first update the
myWordListvalues by assigning a new object to each value. These new objects have two properties: avalueproperty that is assigned the oldmyWordList.word#value, and a newdescriptionproperty that describes the word. Next, I update the unordered list by replacing the word values with the word descriptions.Edit:
If you want to loop over the properties in the object, you can do this: