2012-10-20 306 views
0

我正在创建一个数据数组,然后使用json_encode,然后将其存储在我的数据库中。现在,我试图做的是从数据库中返回它们,并在foreach循环中使用它们,但我无法工作。从数据库中的字符串重新创建json对象

这就是它看起来像在数据库:

["483","482"] 

我希望能够做这样的事情:

$json = ["483","482"]; //(note, this would be the value directly from the database) 

foreach($json as $photoID) 
{ 
    echo $photoID; 
} 

我再次使用json_encode试过了,显然没”工作。它只是retunred: “[” 483" , “482”]”

回答

3

您应该使用json_decode将其返回到PHP数组。 json_decode

所以,当你有php变量并且想要json时,使用php_encode,并且如果你想以其他方式使用json_decode。

编辑:

试试这个例子:

// PHP Array 
$array = array(483, 482); 

var_export($array); 
echo "<br />"; 

// Goes into JSON 
$json = json_encode($array); 

var_export($json); 
echo "<br />"; 

// And back to PHP array 
$backToArray = json_decode($json); 

var_export($backToArray); 
echo "<br />"; 

这将输出:

array (0 => 483, 1 => 482,) 
'[483,482]' 
array (0 => 483, 1 => 482,) 

这应该工作。

+0

我已经使用过这个,但是它没有返回任何东西。 –

+0

你确定你使用了不同的功能,DEcode和ENcode,这应该是真的。你运行什么PHP版本? – otporan

+0

这是我的错误,原来是一个变量,我没有注意到一个htmlenties。 –

0

你试过json_decode,解码JSON字符串

+0

是的我有,那不会返回任何东西。 –

+1

@DylanCross'json_decode'客观上是正确的答案。如果这不适合你,那么问题在别处。 –

+0

如果你从db打印出字符串,你会得到什么? – wgcrouch

0

使用json_decode($data,TRUE),这会给你阵列

见工作代码:http://codepad.org/HVNOuGmY

$c = '["483","482"]'; 

echo "<pre>"; 
print_r (json_decode($c,TRUE)); 
+0

这是我尝试的第一件事,但没有任何回报。 –

+0

在这里看到工作代码:http://codepad.org/HVNOuGmY – GBD