0

I am fetching data from my DB and they look like this:

[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}] 

where the key-1 are the name of the column. (I only have one entry so).

I want to extract only the column values and save them into a new array that will output like this:

{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"} 

I want it to look exactly like this and not : [{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}]

I tried this:

$cart["key-1"]=$output["key-1"];

where $output is the outcome of the DB that shown first (the one with []).

and the $cart is the new array I want.

Both are declared as:

$cart=array();
$output=array();

and $output[]=$row where row is the result of the DB fetch. How to do it?

4

3 回答 3

1

这是一种方法,我在这里用数据库行替换了一个字符串,并使用了json_decode()andjson_encode()

$data = '[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]';

// convert to an array
$data = json_decode($data, true);

// create new array here
$cart = array();

for ($i = 0; $i < count($data); $i++)
{
    foreach ($data[$i] as $k => $v)
    {
        if (strpos($k, 'key') !== FALSE)
        {
            $cart[$k] = $v;
        }
    }
}

echo $cart['key-1'] . '<br/>';

echo json_encode($cart);

输出:

1
{"key-1":"1","key-2":"1","key-3":"1","key-4":"1"}
于 2012-12-15T11:29:24.227 回答
0

这是一个非常混乱的问题。从我收集到的你想要的可能是这个..?

$cart=array();
foreach ($output as $index=>$value){
  if stripos($index,"key-"){
    cart[$index]=$value;
  }
}
于 2012-12-15T11:27:49.707 回答
0

用于mysql_fetch_assoc()仅获取列名;)

while ($row = mysql_fetch_assoc($result_of_query))
{
    echo $row['key-1'];
    echo $row['key-2'];
}
于 2012-12-15T11:28:46.010 回答