Why is it only showing 2 out of the 3 arrays?
I'm not sure why this is happening. Here is my XML:
<ResultSet>
<chats>
<chat>
<messages>
<sms>
<from>Bisma Iqbal</from>
<msg>Hi</msg>
<sent>1311612055</sent>
</sms>
<sms>
<from>Bisma Iqbal</from>
<msg>Hi</msg>
<sent>1311612068</sent>
</sms>
<sms>
<from>Bisma Iqbal</from>
<msg>Hi</msg>
<sent>1311612074</sent>
</sms>
<sms>
<from>Bisma Iqbal</from>
<msg>Hi</msg>
<sent>1311612186</sent>
</sms>
</messages>
<contact>Bisma Iqbal</contact>
</chat>
<chat>
<messages>
<sms>
<from>Javaid Iqbal</from>
<msg>this is the first message</msg>
<sent>1311612055</sent>
</sms>
<sms>
<from>Javaid Iqbal</from>
<msg>this is the second message</msg>
<sent>1311612055</sent>
</sms>
</messages>
<contact>Javaid Iqbal</contact>
</chat>
<chat>
<messages>
<sms>
<from>Ankur Shahi</from>
<msg>Wanna play dawg at 7:15</msg>
<sent>1311632708</sent>
</sms>
<sms>
<from>Ankur Shahi</from>
<msg>Wanna play dawg at 7:15</msg>
<sent>1311632708</sent>
</sms>
<sms>
<from>Ankur Shahi</from>
<msg>Wanna play dawg at 7:15</msg>
<sent>1311632708</sent>
</sms>
</messages>
<contact>Ankur Shahi</contact>
</chat>
</chats>
</ResultSet>
Now, here is my code:
require_once('global.php');
$statement = $db->prepare("SELECT * FROM user WHERE id=1");
$statement->execute();
$result = $statement->fetchObject();
$string = $result->chats;
$chats = GBA($string, "<chat>", "</chat>"); //the XML I showed you
for($i = 0, $size = count($chats); $i 开发者_Go百科< $size; ++$i) {
//for every chat:
$all_sms = GBA($chats[$i], "<sms>", "</sms>");
$name = GB($chats[$i], "<contact>", "</contact>");
echo "<center><table border='1' cellpadding='5'><tr><td colspan='3' align='center'>SMS Chat with <i>{$name}</i></td></tr><tr><th>From</th><th>Message</th><th>Sent</th></tr>";
for($j = 0, $size = count($all_sms); $j < $size; ++$j) {
//for every sms in each chat
$from = GB($all_sms[$j], "<from>", "</from>");
$msg = GB($all_sms[$j], "<msg>", "</msg>");
$sent = time_since(GB($all_sms[$j], "<sent>", "</sent>"));
echo "<tr><td>{$from}</td><td>{$msg}</td><td>Sent: {$sent} </td></tr>";
}
echo "</table><br /><br /></center>";
}
As you can see, everything looks fine but it only shows the first 2 tables, not the third! I have a debugged a lot to no conclusion.
You used $size
in the outer loop, and $size
in the inner loop.
PHP has no block scope, so this is the same variable. As it changes in the inner loop, you're messing up your outer loop.
Pick a different name for the variable in the inner loop.
Inside the inner loop you reassign $size. The second chat group of sms has only 2 entries which causes the outer loop to terminate since $size = 2 and $i = 2. Jon Martin's suggestion appears to work for your specific data but will fail in general case.
I suggest
for($j = 0, $jsize = count($all_sms); $j < $jsize; ++$j) {
// ...
精彩评论