查找Json行号

时间:2014-07-20 11:30:46

标签: php

我有一个Json行数据,并希望使用php将其转换为mysql数据库。

我正在使用

$file = file_get_contents($path); $data = json_decode($file, TRUE);

将Json文件解码为数组。

这很好但会返回整个文件。我想引用一个特定的行,例如解码第3行到第6行的json文件(应该从" id:FR08"到" id:" ES01" )并忽略其余的行。请告知如何以Json行格式返回行号,我似乎无法找到代码。

以下是数据样本:

{"profile":[    
 {"id":"UK01","num_connections":"270","locality":"UK","industry":"Accounting"}  
,{"id":"ES03","locality":"Spain","experience":[{"start":"2003","organization":[{"name":"org1"}],"end":"Presente","title":"Director"},{"start":" 1995","organization":[{"name":"org2"}],"end":"2003","title":"Manager"}]} 
,{"id":"FR08","num_connections":"10","locality":"France","experience":[{"organization":[{"name":"org1","details":""}],"title":"Manager"}],"industry":"Construction"}   
,{"id":"AD04","num_connections":"68","locality":"Andorra"}   
,{"id":"GE02","locality":"Germany"}  
,{"id":"ES01","num_connections":"450","experience":[{"organization":[{"details":""}],"title":"Directora"}],"industry":"Construction"}  
,{"id":"UK06","num_connections":"1","locality":"Andorra","full_name":"Joana Marisa Sacramento Carvalhais"}     
]}

2 个答案:

答案 0 :(得分:2)

您还可以使用array_filter解决方案:

$file = file_get_contents($path); 
$data = json_decode($file, TRUE);
$flag = array(
    False,
    False,
    True, // line no 3
    True, // line no 4
    True, // line no 5
    True, // line no 6
    False,
    );
function fil($var)
{
    global $flag;
    return $flag[$var];
}

$data = array_filter($data, "fil");

答案 1 :(得分:0)

只需过滤您的数组。

$file = file_get_contents($path); 
$data = json_decode($file, TRUE);
$saving = false;

foreach($data['profile'] as $index => $item)
{
    if($item['id'] == 'FR08')
    {
       $saving = true;
    }

    if($saving === false)
    {
       unset($data['profile'][$index]);
    }

    if($item['id'] == 'ES01')
    {
        $saving = false;
        break;
    }
}