【问题标题】:android - displays the data array with foreach on mysqlandroid - 在 mysql 上使用 foreach 显示数据数组
【发布时间】:2014-05-14 06:42:44
【问题描述】:

如何以foreach的方式显示存储在mysql中的数据?我想使用 foreach 显示来自 mysql darabase 的数据。我尝试了下面的 tes2.php 文件,但不是我需要的。

trans.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MenuActivity extends ListActivity {
    ConnectionDetector cd;  
    AlertDialogManager alert = new AlertDialogManager();    
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    ArrayList<HashMap<String, String>> submenu;
    JSONArray menu = null;
    private static final String URL_ALBUMS = "http://10.0.2.2/android/tes.php";

    // ALL JSON node names
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_TYPE_COUNT = "type_count";

tes.php // 成功,但不使用mysql :(

<?php

include_once './data.php'; //"with data.php????" :( not use mysql
$trans = array();

foreach ($tran_z as $trans) {
    $tmp = array();
    $tmp["id"] = $album["id"];
    $tmp["name"] = $album["name"];
    $tmp["type_count"] = count($trans["type"]);

    array_push($trans, $tmp);
}

echo json_encode($trans);
?>

tes2.php //不成功 :(

<?php
include("connect.php");
$q = mysql_query("SELECT * FROM tbl1");
$trans = '[';
while($r=mysql_fetch_array($q))
{
    if(strlen($v)<15)
    {
        $trans .= '{ 
            "id" :"'.($r['id']).'",
            "name" : "'.$r['name'].'",
            "type_count" : "'.$r['type'].'"
            }';
    }
    else
    {
        $trans .= '{ 
            "id" :"'.($r['id']).'",
            "name" : "'.$r['name'].'",
            "type_count" : "'.$r['type'].'"
            }';

    }
}
$trans .= ']';
    echo json_encode($trans);
?>

【问题讨论】:

  • 去掉 echo json_encode($trans); 在 test2.php 中添加 echo $trans; 因为 $trans 已经是一个字符串了。
  • 不显示....和错误

标签: php android mysql arrays foreach


【解决方案1】:
<?php
include("connect.php");
$q = mysql_query("SELECT * FROM tbl1");
$trans = array();
while($r=mysql_fetch_array($q))
{

        $trans[] = $r;

}

    echo json_encode($trans);
?>

如果你想要关联数组,只需更改这个 mysql_fetch_array($q, MYSQL_ASSOC) i while .

【讨论】:

  • 非常感谢,...这是成功的,但没有显示给 $tmp["type_count"] = count($trans["type"]);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 2021-04-17
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多