需要使用相同的键和值对计算数组吗?

时间:2018-03-22 08:11:03

标签: php json

我有一个json数组:

[{"id":447,"file_format":"abc","language":"af"},{"id":449,"file_format":"abc","language":"af"},{"id":453,"file_format":"abc","language":"afs"},{"id":454,"file_format":"def","language":"afs"}]

我如何在php中操作这个数组,以便我可以得到一个结果:

 [
    {"file_format":abc,"count":"2","language":"af"},
    {"file_format":abc,"count":"1","language":"afs"},
    {"file_format":def,"file_format":"1","language":"afs"}
  ]

我已经尝试过数组计数值,它返回单维数组的结果。任何帮助都会很有帮助,谢谢。

我的代码:

foreach($occurences as $lsvariable){
            $lvariable[$lsvariable['file_format']][$lsvariable['language']]=0;
        }
         //return $lvariable;
        foreach ($occurences as $occurence) {


              $lvariable[$occurence['file_format']][$occurence['language']]++;

           $language = $occurence['language'];
           $file_format = $occurence['file_format'];
        }

        return $lvariable;

这解决了我的目的,但是真的需要2个循环吗?

1 个答案:

答案 0 :(得分:0)

您可以使用reduce使用密钥创建关联数组:language-file_format

然后要转换为简单数组,您可以使用array_values

$arr = '[{"id":447,"file_format":"abc","language":"af"},{"id":449,"file_format":"abc","language":"af"},{"id":453,"file_format":"abc","language":"afs"},{"id":454,"file_format":"def","language":"afs"}]';
$arr = json_decode( $arr, true );

$newArr = array_reduce($arr, function($c,$v){
    $key = $v["language"] . "-" . $v["file_format"];

    if ( !isset( $c[$key] ) ) $c[$key] = array( "file_format" => $v["file_format"], "language" => $v["language"], "count" => 1 );
    else $c[$key]["count"]++;

    return $c;
}, array());

$newArr = array_values( $newArr );

echo "<pre>";
print_r( $newArr );
echo "</pre>";

这将导致:

Array
(
    [0] => Array
        (
            [file_format] => abc
            [language] => af
            [count] => 2
        )

    [1] => Array
        (
            [file_format] => abc
            [language] => afs
            [count] => 1
        )

    [2] => Array
        (
            [file_format] => def
            [language] => afs
            [count] => 1
        )

)