在mysql上显示带有foreach的数据数组

时间:2014-05-14 05:23:02

标签: php android mysql arrays foreach

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

TBL1

+-----+----------+--------+
|*id  |   name   |  type  |
+=====+==========+========+
|  1  |   car    |   a    |
+-----+----------+--------+
|  2  | motorcly |   a    |
+-----+----------+--------+
|  3  |   Bus    |   1    |
+-----+----------+--------+
|  4  |   others |   1    |
+-----+----------+--------+

file.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);
?>

此示例涉及foreach但不使用mysql

tes.php

<?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);
?>

如何以foreach的方式显示存储在mysql中的数据?

package com.trans.baru;

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";

1 个答案:

答案 0 :(得分:0)

首先填充一个数组?

include("connect.php");
$q = mysql_query("SELECT * FROM tbl1");
$rs = array();
while($r=mysql_fetch_array($q)) {
    $rs[] = $r;
}
foreach ($rs as $r) {
    //do stuff
}

顺便说一下,您自己拼凑了一个JSON字符串,然后json_encode然后将它拼凑起来......只需制作数组,然后让{{1}做编码。 IE浏览器。 json_encode