doujiyan0031
doujiyan0031
2009-12-07 13:36

无法在Ubuntu中迭代对象PHP 5.2.10-2适用于PHP 5.2.10吗?

已采纳

With this code I am iterating through an object.

Works:

  • Windows with WAMP and PHP 5.2.9
  • Linux web server with PHP 5.2.10

It is not working on my desktop:

  • Ubuntu 9.10 with PHP 5.2.10-2 from the repo's
$incomingData = json_decode($_POST['data']);

foreach($incomingData as $key => $action)
{

}

Invalid argument supplied for foreach()

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongyang5716 dongyang5716 12年前

    Maybe one of your servers has magic_quotes_gpc enabled, so you can try to use stripslashes on $_POST['data'] before you decode it. Both PHP versions should be able to iterate through objects.

    点赞 评论 复制链接分享
  • dqqn32019 dqqn32019 12年前

    try doing:

    $data_array = get_object_vars(json_decode($json_data));
    
    print_r($data_array);
    
    this is only if you obtain information from some web page such as
    
    $data = file_get_contents('http://www.someurl.com/somerestful_url/');
    $data_array = get_object_vars(json_decode($data));
    print_r($data_array);
    

    also, you were probably trying to do json_encode, but instead put json_decode($_POST['data']);

    unless you have json string inside of $_POST['data']; it will not work.

    点赞 评论 复制链接分享
  • douxianglu4370 douxianglu4370 12年前

    Are you sure you've got your PHP versions right?

    From the documentation for foreach:

    As of PHP 5, it is possible to iterate objects too.

    Try using json_decode with the second argument set to true, to make json_decode return associative arrays rather than objects.

    $incomingData = json_decode($_POST['data'], true);
    

    Where the second argument, $assoc (defaults to false) means:

    When TRUE, returned objects will be converted into associative arrays.

    My guess is that one box has less than PHP 5.

    To confirm that's the issue, try changing $incomingData to some kind of innocuous associative array:

    $incomingData = array("foo" => "bar", "baz" => "monkey");
    

    and see if that makes the error go away.

    点赞 评论 复制链接分享