Я хочу получить количество записей о странах в многомерном массиве. Я также хотел бы получить такое же количество, но отфильтрованное по записи, так что количество Нидерландов. Я пробовал это: $ total = ...

2
Spatial Digger 16 Янв 2021 в 03:59

3 ответа

Лучший ответ

Количество записей country:

$dataCountry = array_column($data, 'country');
echo "total: ", count($dataCountry);

Количество The Netherlands:

$dataCountryCount = array_count_values(array_filter($dataCountry));
echo $dataCountryCount['The Netherlands'] ?? 0;

Фильтр множественного поиска:

$filter = ['country' => 'The Netherlands', 'continent' => 'Europe'];
$dataFilter = array_filter($data, function($item) use ($filter) {
    return $filter == array_intersect_key($item, $filter);
});
echo 'total:', count($dataFilter);

print_r($dataFilter);
2
user14717238 16 Янв 2021 в 12:55

Вы можете попробовать это ниже:

  $data = json_decode($data_json,true);

  echo count_filtered_by($data);
  // Returns (int) 3
  echo count_filtered_by($data,'country');
  // Returns (int) 3
  echo count_filtered_by($data,'country','The Netherlands');
  // Retruns (int) 2
  echo count_filtered_by($data,'country','UK');
  // Returns (int) 1
  echo count_filtered_by($data,'country','uK',true);
  // Returns (int) 0

  /**
  * Count filtered by
  * 
  * @param array $data
  * @param string|nullable $key
  * @param string|nullable $value
  * @param bool $strict Default is (Case Insensitive)
  * 
  * @return int count filtered by
  */
  function count_filtered_by($data,$key = NULL,$value = NULL,$strict = false) {
    $column = array_column($data,$key);
    if($key === NULL) return count($data);
    if($value === NULL ) return count($column);
    // Remove empty values
    $filtered = array_filter($column);

    $count = 0;
    foreach($filtered as $column) {
      if(!$strict) {
        $column = strtolower($column);
        $value = strtolower($value);
      }
      if($column === $value) $count++;
    }

    return $count;
  }

Итак, я проверяю ваши данные здесь

  $data_json = '[
      {
          "higherGeographyID": "http:\/\/vocab.getty.edu\/tgn\/7016845",
          "higherGeography": "None",
          "continent": "Europe",
          "waterBody": "None",
          "islandGroup": "None",
          "island": "None",
          "country": "The Netherlands",
          "countryCode": "NL",
          "stateProvince": "Groningen",
          "county": "Groningen",
          "municipality": "Groningen",
          "locality": "Groningen",
          "verbatimLocality": "None",
          "minimumElevationInMeters": "None",
          "maximumElevationInMeters": "None",
          "verbatimElevation": "None",
          "minimumDepthInMeters": "None",
          "maximumDepthInMeters": "None",
          "verbatimDepth": "None",
          "minimumDistanceAboveSurfaceInMeters": "None",
          "maximumDistanceAboveSurfaceInMeters": "None",
          "locationAccordingTo": "None",
          "locationRemarks": "None",
          "decimalLatitude": "None",
          "decimalLongitude": "None",
          "geodeticDatum": "None",
          "coordinateUncertaintyInMeters": "None",
          "coordinatePrecision": "None",
          "pointRadiusSpatialFit": "None",
          "verbatimCoordinates": "None",
          "verbatimLatitude": "None",
          "verbatimLongitude": "None",
          "verbatimCoordinateSystem": "None",
          "verbatimSRS": "None",
          "footprintWKT": "None",
          "footprintSRS": "None",
          "footprintSpatialFit": "None",
          "georeferencedBy": "None",
          "georeferencedDate": "None",
          "georeferenceProtocol": "None",
          "georeferenceSources": "None",
          "georeferenceVerificationStatus": "None"
      },
      {
          "higherGeographyID": "http:\/\/vocab.getty.edu\/tgn\/7016845",
          "higherGeography": "None",
          "continent": "Europe",
          "waterBody": "None",
          "islandGroup": "None",
          "island": "None",
          "country": "The Netherlands",
          "countryCode": "NL",
          "stateProvince": "Groningen",
          "county": "Groningen",
          "municipality": "Groningen",
          "locality": "Groningen",
          "verbatimLocality": "None",
          "minimumElevationInMeters": "None",
          "maximumElevationInMeters": "None",
          "verbatimElevation": "None",
          "minimumDepthInMeters": "None",
          "maximumDepthInMeters": "None",
          "verbatimDepth": "None",
          "minimumDistanceAboveSurfaceInMeters": "None",
          "maximumDistanceAboveSurfaceInMeters": "None",
          "locationAccordingTo": "None",
          "locationRemarks": "None",
          "decimalLatitude": "None",
          "decimalLongitude": "None",
          "geodeticDatum": "None",
          "coordinateUncertaintyInMeters": "None",
          "coordinatePrecision": "None",
          "pointRadiusSpatialFit": "None",
          "verbatimCoordinates": "None",
          "verbatimLatitude": "None",
          "verbatimLongitude": "None",
          "verbatimCoordinateSystem": "None",
          "verbatimSRS": "None",
          "footprintWKT": "None",
          "footprintSRS": "None",
          "footprintSpatialFit": "None",
          "georeferencedBy": "None",
          "georeferencedDate": "None",
          "georeferenceProtocol": "None",
          "georeferenceSources": "None",
          "georeferenceVerificationStatus": "None"
      },
      {
          "higherGeographyID": "http:\/\/vocab.getty.edu\/tgn\/7016845",
          "higherGeography": "None",
          "continent": "Europe",
          "waterBody": "None",
          "islandGroup": "None",
          "island": "None",
          "country": "UK",
          "countryCode": "UK",
          "stateProvince": "Groningen",
          "county": "Groningen",
          "municipality": "Groningen",
          "locality": "Groningen",
          "verbatimLocality": "None",
          "minimumElevationInMeters": "None",
          "maximumElevationInMeters": "None",
          "verbatimElevation": "None",
          "minimumDepthInMeters": "None",
          "maximumDepthInMeters": "None",
          "verbatimDepth": "None",
          "minimumDistanceAboveSurfaceInMeters": "None",
          "maximumDistanceAboveSurfaceInMeters": "None",
          "locationAccordingTo": "None",
          "locationRemarks": "None",
          "decimalLatitude": "None",
          "decimalLongitude": "None",
          "geodeticDatum": "None",
          "coordinateUncertaintyInMeters": "None",
          "coordinatePrecision": "None",
          "pointRadiusSpatialFit": "None",
          "verbatimCoordinates": "None",
          "verbatimLatitude": "None",
          "verbatimLongitude": "None",
          "verbatimCoordinateSystem": "None",
          "verbatimSRS": "None",
          "footprintWKT": "None",
          "footprintSRS": "None",
          "footprintSpatialFit": "None",
          "georeferencedBy": "None",
          "georeferencedDate": "None",
          "georeferenceProtocol": "None",
          "georeferenceSources": "None",
          "georeferenceVerificationStatus": "None"
      }
  ]';
0
Jerson 16 Янв 2021 в 05:42

Если я правильно вас понял, вы могли бы сделать это:

//Example data for testing
$arr = [
    ['a'=> ['country' => 'Netherland']],
    ['e'=> ['country' => 'Netherland']],
    ['b'=> ['country' => 'Sweden']],
    ['c'=> ['country' => 'Netherland'], 'a' => ['country' => 'Netherland']],
    ['f'=> ['country' => 'Sweden']],
];

//Init som global variables 
$count_countries = 0; //Number of occurences of 'country'
$check_country = 'Netherland'; //What country to check
$count_country = 0; //Number of occurences for chosen country to check

//Walk through array recursively and count each found occurence of 
//country and the actual country to check
array_walk_recursive($arr, function($item, $key) {
    global $count_countries, $count_country, $check_country;
    if ($key == 'country') $count_countries++;
    if ($item == $check_country) $count_country++;
});

//Output result
echo 'count for ' . $check_country . ' = ' . $count_country . '<br>';
echo 'count for countries = ' . $count_countries;

Результат в этом случае:

count for Netherland = 4
count for countries = 6
0
bestprogrammerintheworld 16 Янв 2021 в 09:37
65745479