使用数组循环数组

时间:2018-04-26 12:41:02

标签: php

我真的需要一些帮助。

我有一个SQL查询,可以选择正确的表格列。

但是,我想循环数据的内容,但是当我这样做时,我得到以下结果:

["",""]
["Pretoria"]
["",""]
wc
["Pretoria","Cape Town","Garden Route"]
[""]
[""]

我如何才能获得[""]?

中的项目
if (isset($_GET['category'])) {
    $catetogry = $_GET['category'];
    $name = $_GET['name'];

    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query = ("SELECT * FROM #__jsn_users");
    $db->setQuery($query);
    $results = $db->loadObjectList();


    foreach($results as $obj) {

        $value = $obj->suburbs_i_cover;

        if(!empty($value)){
            echo $value;
            echo"<br>";
        }
    }
}


Output: var_dump($obj->suburbs_i_cover);
NULL NULL string(0) "" string(7) "["",""]" ["",""]
string(12) "["Pretoria"]" ["Pretoria"]
string(0) "" string(7) "["",""]" ["",""]
string(0) "" string(2) "wc" wc
string(0) "" string(39) "["Pretoria","Cape Town","Garden Route"]" 
["Pretoria","Cape Town","Garden Route"]
string(4) "[""]" [""]
string(4) "[""]" [""]
string(0) "" string(27) "["Pretoria","Johannesburg"]" 
["Pretoria","Johannesburg"]
string(34) "["Hartbeespoort Dam","Klerksdorp"]" ["Hartbeespoort 
Dam","Klerksdorp"]
string(47) "["Port Elizabeth","Jeffreys Bay","East London"]" ["Port 
Elizabeth","Jeffreys Bay","East London"]
string(47) "["Port Elizabeth","Jeffreys Bay","East London"]" ["Port 
Elizabeth","Jeffreys Bay","East London"]

2 个答案:

答案 0 :(得分:0)

我不确定["Pretoria","Cape Town","Garden Route"]字符串来自哪里,但它似乎是用json_decode()解码的好候选人

foreach($results as $obj) {

    // Try to treat each suburbs_i_cover as a JSON string
    // and decode it to a native PHP array
    $value = json_decode($obj->suburbs_i_cover);

    // If we have an array then we can loop it
    if(is_array($value)) {
        foreach($value as $sub_value) {
            echo 'sub_value: '.$sub_value.'<br>';
        }
    }
    else {
        // The json_decode() did not result in an array so show the original value
        echo 'not array: '.$obj->suburbs_i_cover.'<br>';
    }
}

答案 1 :(得分:-1)

看起来你得到另一个阵列?尝试在

内再次做到
foreach($results as $obj) {

 $value = $obj->suburbs_i_cover;

    if(!empty($value)){
        foreach($value as $x) {  
         echo $x;
         echo"<br>";
        }
    }
}
相关问题