json multidimensional array and jquery?
I create this output with PHP:
foreach ($bk as $blink) { $out["url"][] = $blink->url; $out["anchor"][] = $blink->anchor; }
$json = Zend_Jso开发者_如何学Cn::encode($out); echo ($json);
I want to receive and process the output with a $.ajax call.
Could you point me to a nice tutorial about multidimensional arrays with javascript/jquery or help me loop* through the json results? I got a bit confused with it.
- I am trying to put those on a table, so I will be using
<td>url-i</td><td>anchor-i</td>
. This part, I figured out how. To put the correct values onurl-i
andanchor-i
is the problem.
I would imagine the JSON output for that will be something like:
{'url': ['url1', 'url2', ... ],
'anchor': ['anchor1', 'anchor2', ... ]}
If that is the case, then they will be of equal length (and importantly equal indexes) and you can loop through one of the two using jQuery.each().
$.getJSON('jsonapp.php', function(data) {
$.each(data.url, function(index, url) {
var anchor = data.anchor[index];
$('#mytable').append('<tr><td>' + url + '</td><td>' + anchor +'</td></tr>');
});
});
I've not run that code, so it might have a few flaws, but that's the gist of it.
PHP can try to cast objects into arrays by itself, and for simple stuff, it usually works fine.
As for multidimensional arrays, Javascript isn't too different from most other higher-level programming/scripting languages when it comes to arrays. Really, any tutorial online on multidimensional arrays will do just fine. A multidimensional array is simply an array of arrays.
When you receive the string client-side, you just want to parse it. jQuery has its own method, but you can use JSON.parse. Afterwards, based on how you've set up your arrays, you'd want to do something like this.
<? $count = count($json_parsed['url']); for($i = 1; $i < $count; $i++) : ?>
<td><?=$json_parsed['url'][$i];?></td>
<td><?=$json_parsed['anchor'][$i];?></td>
<? endfor; ?>
This may be philosophically not the best way to do it though. If you have a whole bunch of objects and you want to make a table out of them, the best way would be to create an array of those objects as represented by associative arrays (sort of like hash tables in other programming languages). PHP natively tries to convert objects into associative arrays. I wouldn't be surprised if Zend_Json::encode
does it automatically. If it does, you might want to pull simply:
echo Zend_Json::encode($bk);
If not, let me know, and we'll talk about how to do that.
You could have a look on any template frameworks, but for this exact case it seams useful to check one of those two: pure by beebole or jquery pure html templates.
Doing it by yourself might be tempting but why to reinvent the well - I know from my experience, that frameworks are about 2 times faster, then self made code.
精彩评论