用PHP分析JSON

时间:2017-12-04 00:26:16

标签: php json

我有一些问题保留工程JSON文件将由PHP脚本分析。分析JSON的PHP代码如下:

// New search / info file
$a_info = json_decode( file_get_contents( 'data/vehicles.json' ), true );

// Makes / Years options
$a_year = array();
$a_make = array();

foreach( $a_info AS $ai ) {

    if( $ai[0]['make'] )
        var_dump($ai);
        if( array_key_exists( $ai[0]['make'], $a_make ) )
            $a_make[$ai[0]['make']] = $a_make[$ai[0]['make']] + 1;
        else
            $a_make[$ai[0]['make']] = 1;

    if( $ai[0]['year'] )
        if( array_key_exists( $ai[0]['year'], $a_year ) )
            $a_year[$ai[0]['year']] = $a_year[$ai[0]['year']] + 1;
        else
            $a_year[$ai[0]['year']] = 1;

}

// Sort the make / years arrays
krsort( $a_year );
ksort( $a_make );

var_dump($a_make);

// New listing file
$a_list = json_decode( file_get_contents( 'data/list.json' ), true );

foreach( $a_list['listing_ids'] AS $index => $id ) {

    if( isset( $_GET['year'] ) )
        if( $a_info[$id][0]['year'] != $_GET['year'] )
            unset( $a_list['listing_ids'][$index] );

    if( isset( $_GET['make'] ) )
        if( $a_info[$id][0]['make'] != $_GET['make'] )
            unset( $a_list['listing_ids'][$index] );

    if( isset( $_GET['search'] ) ) {

        // Check name
        if(
            strpos( strtolower( $a_info[$id][0]['name'] ), $_GET['search'] ) === false
            AND strpos( strtolower( $a_info[$id][0]['body'] ), $_GET['search'] ) === false
            AND strpos( strtolower( $a_info[$id][0]['year'] ), $_GET['search'] ) === false
            AND strpos( strtolower( $a_info[$id][0]['make'] ), $_GET['search'] ) === false
        )
            unset( $a_list['listing_ids'][$index] );

    }

}

我一直在尝试重建JSON,但是我无法在$ a_make或$ a_year PHP数组中显示多个模型或年份。这就是我对JSON的看法:

 {
  "vechiles": [
    {
      "make": "Accura",
      "year": "2006"
    },
    {
      "make": "BMW",
      "year": "200"
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

$a_info = json_decode('{"vehicles":[{"year":"2006"},{"make":"BMW","year":"200"},{"make":"BMW","year":"200"},{"make":"BMW","year":"2007"},{"make":"Accura","year":"200"}]}');

$a_year = array();
$a_make = array();

foreach ($a_info->vehicles as $vehicle) {
if (isset($vehicle->make)) {
    if ( array_key_exists( $vehicle->make, $a_make ) ) {
        $a_make[$vehicle->make] = $a_make[$vehicle->make] + 1;
    } else {
        $a_make[$vehicle->make] = 1;
    }
}

if (isset($vehicle->year)) {
    if (array_key_exists($vehicle->year, $a_year)) {
        $a_year[$vehicle->year] = $a_year[$vehicle->year] + 1;
    } else {
        $a_year[$vehicle->year] = 1;
    }
}
}

krsort($a_year);
ksort($a_make);

var_dump($a_make, $a_year);