2013-07-27 44 views
0

滤波器阵列我有一个这样的数组这是我从解析HTML源代码有:我怎样才有效对象在PHP

Array 
(
    [0] => 12345 
    [1] => 54321 
    [2] => 32546 
    [3] => 98754 
    [4] => 15867 
    [5] => 75612 
) 

,如果我把它放在一个变量,并运行foreach循环前缀像这样一个网址:

$x = Array; 
foreach ($x as $y){ 
$r = 'http://example.com/' . $y; 
echo $r . '<br>'; 
} 

它会像这样的输出:

http://example.com/12345 
http://example.com/54321 
http://example.com/32546 
http://example.com/98754 
http://example.com/15867 
http://example.com/75612 

而且每个输出的URL,如果运行的兄弟wser将输出的对象无论是这样的:

{ 
    "key1": "value1", 
    "key2": "value2", 
    "key3": "value3" 
} 

OR这样的:

{ 
    "error": { 
     "errorMessage": "errorMessageValue", 
     "errorType": "errorTypeValue" 
    } 
} 

所以我的问题是...我怎么筛选PHP中的数组,这样只会给我一个具有有效键/值对而不是错误对象的数组。

所建议的,我尝试以下:

$x = Array; 
foreach ($x as $y){ 
$link = 'http://example.com' . $y; 
$json = file_get_contents($link); 
$array = array_filter((array)json_decode($json), "is_scalar"); 
echo '<pre>'; 
echo json_encode($array) . '<br>'; 
echo '</pre>'; 
} 

,但它仍然输出相同的数组,并且不排除错误对象。

+1

请添加额外信息,在哪里生成该数组?除非第二个参数设置为true – 2013-07-27 00:35:29

回答

4
$array = array_filter((array)json_decode($json), "is_scalar"); 

这将排除数组中的所有对象,并且只有key =>值对,其中value不是对象也不是数组。

+1

json_decode返回一个对象,我得到'注意:数组字符串conversion'试图使用'file_get_contents'得到时'$ json'工作,然后回显'$ array' – Martin

+0

@马丁没关系,加入数组转换使用您的代码;-) – bwoebi

+0

@bwoebi – anagnam

0

也许我失去了一些东西,但你不能只检查是否返回的对象包含一个“错误”条目,如果是这样,跳过?

$x = Array; 
foreach ($x as $y){ 
    $link = 'http://example.com' . $y; 
    $json = file_get_contents($link); 
    $returned_data = json_decode($json, true); 

    // If returned data contains an "error" entry, just move to next one 
    if(isset($returned_data['error'])) { 
    continue; 
    } 
    echo '<pre>'; 
    echo json_encode($returned_data) . '<br>'; 
    echo '</pre>'; 
}