简体   繁体   English

将MySQL查询结果拆分为多维数组

[英]Splitting a MySQL Query result into an multidimensional-array

I have the following result from a MySQL query with two joins. 我从具有两个联接的MySQL查询中得到以下结果。

Array ( 
[0] => Array ( [place_id] => 1 [place] => Berlin [lat] => 52.519 [lon] => 13.406 [id] => 1 [pname] => Firstschool [typ] => 0 [s_id] => 32 [fac] => history) 

[1] => Array ( [place_id] => 1 [place] => Berlin [lat] => 52.519 [lon] => 13.406 [id] => 1 [pname] => Secondschool [typ] => 0 [s_id] => 33 [fac] => math)

[2] => Array ( [place_id] => 1 [place] => Berlin [lat] => 52.519 [lon] => 13.406 [id] => 1 [pname] => Secondschool [typ] => 0 [s_id] => 33 [fac] => english)
)

The data is redundant at some points, I need it this way: 在某些时候数据是多余的,我需要这样:

Array ( 
  [Berlin] => Array ( [lat] => 52.519 
                      [lon] => 13.406  
                      [schools] => Array([0]=> Firstschool [1]=>Secondschool)
  )

  [OtherCity] => Array ( ... )
)

First, is this okay or exists a better solution? 首先,这还可以还是存在更好的解决方案? =) Second.. how to split it for the needed result. =)第二..如何将其拆分为所需的结果。

I tried it with something like the following code snippet, but it doesn't work as wished. 我用下面的代码片段进行了尝试,但是并没有按预期的那样工作。

foreach($viewmodel as $item) { 
   $data[$item['place']][] = $item['pname'];
}

The result is: 结果是:

Array ( [Berlin] => Array ( [0] => Firstschool [1] => Firstschool [2] => Firstschool ))

NOT so useful. 没那么有用。 ;) ;)

I hope its understandable what I need. 我希望它可以理解我的需求。 Maybe someone has an nice idea how to solve this problem. 也许有人对如何解决这个问题有个好主意。

Thanks for your time. 谢谢你的时间。

I think you are on a right path, just need to fill in a little more detail: 我认为您走在正确的道路上,只需要填写一些细节即可:

$cities = Array (
     Array ( 'place_id' => 1, 'place' => 'Berlin', 'lat' => 52.519, 'lon' => 13.406, 'id' => 1, 'pname' => 'Firstschool', 'typ' => 0, 's_id' => 32, 'fac' => 'history'),
     Array ( 'place_id' => 1, 'place' => 'Berlin', 'lat' => 52.519, 'lon' => 13.406, 'id' => 1, 'pname' => 'Secondschool', 'typ' => 0, 's_id' => 33, 'fac' => 'math'),
     Array ( 'place_id' => 1, 'place' => 'Berlin', 'lat' => 52.519, 'lon' => 13.406, 'id' => 1, 'pname' => 'Secondschool', 'typ' => 0, 's_id' => 33, 'fac' => 'english'),
);

// gather the transformed array in a new array 
$out = array();
foreach ($cities as $city) {
    // the first time we see the place
    if (!isset($out[$city['place']])) {
        // copy over what you want to keep
        $out[$city['place']] = array(
            'lat' => $city['lat'],
            'lon' => $city['lon'],
            'schools' => array($city['pname']),
        );
    } // only add $city['pname'] if we don't have it already
    elseif (!in_array($city['pname'], $out[$city['place']]['schools'])) {
        // we already seen this place, just add to the schools
        $out[$city['place']]['schools'][] = $city['pname'];
    }
}

For the gather faculties too question, use the school names as keys to arrays in the 'schools' key of the top level arrays, populate them like this: (still skipping duplicates): 对于收集教师的问题,也可以使用学校名称作为顶级数组的“ schools”键中数组的键,按如下方式填充它们:(仍然跳过重复项):

foreach ($a as $city) {
    if (!isset($out[$city['place']])) {
        $out[$city['place']] = array(
            'lat' => $city['lat'],
            'lon' => $city['lon'],
            'schools' => array($city['pname'] => array($city['fac'])),
        );
    } else {
        // for convenience and readability, introducing some variables
        $schools = &$out[$city['place']]['schools'];
        $pname = $city['pname'];
        $fac = $city['fac'];

        // if we didn't see this school yet, add it with it's faculty
        if (!isset($schools[$pname])) {
            $schools[$pname] = array($fac);
        } // if we did see this school before but the faculty is new, add it under the school's key
        else if (!in_array($fac, $schools[$pname])) { 
            $schools[$pname][] = $fac;
        }
    }
}

you are right, you have to iterate through the array some way or another. 是的,您必须以某种方式遍历数组。 From the array I have seen, assuming all latitudes and longitudes are the same for all schools, overwriting will not hurt, otherwise, additional logic is needed 从我所看到的数组中,假设所有学校的所有纬度和经度都相同,则覆盖不会受到影响,否则,需要附加逻辑

foreach($viewmodel as $item) {
  $data[$item['place']['lat']=$item['lat'];
  $data[$item['place']['long']=$item['lon'];
  $data[$item['place']['schools'][]=$item['pname'];
}

You could map the array using a lambda function if you're using php 5.3+ 如果您使用的是php 5.3+,则可以使用lambda函数映射数组

$output = array();

$sort_schools = function($value, $key)
{
    if ( ! is_array($output[$value['place'])
    {
        $output[$value['place'] = array();
    }

    if ( ! isset($output[$value['place']['lat'] && ! isset($output[$value['place']]['lon'])
    {
        $output[$value['place']]['lat'] = $value['lat'];

        $output[$value['place']]['lon'] = $value['lon'];
    }

    $output[$value['place']]['schools'][] = $value['pname'];
};

array_map($sort_schools, $viewmodel);

Alternatively you could use a similar structure in the lambda function within a foreach loop or an anonymous function. 或者,您可以在foreach循环或匿名函数的lambda函数中使用类似的结构。

The following should yield the described expected result 以下应该产生所描述的预期结果

$arr =  array( 
            array(  'place_id'  => 1,  'place'  => 'Berlin',  'lat'  => 52.519,  'lon'  => 13.406,  'id'  => 1,  'pname'  => 'Firstschool',  'typ'  => 0,  's_id'  => 32,  'fac'  => 'history'),
            array(  'place_id'  => 1,  'place'  => 'Berlin',  'lat'  => 52.519,  'lon'  => 13.406,  'id'  => 1,  'pname'  => 'Secondschool',  'typ'  => 0,  's_id'  => 32,  'fac'  => 'history'),
            array(  'place_id'  => 1,  'place'  => 'Berlin',  'lat'  => 52.519,  'lon'  => 13.406,  'id'  => 1,  'pname'  => 'Secondschool',  'typ'  => 0,  's_id'  => 32,  'fac'  => 'history')
            );

$result = array();

foreach($arr as $item) {
    if (array_key_exists($item['place'], $result)) {
        if (!in_array($item['pname'], $result[$item['place']]['schools'])) {
            array_push($result[$item['place']]['schools'], $item['pname']);
        }
    } else {
        $result[$item['place']]['lat'] = $item['lat'];
        $result[$item['place']]['lon'] = $item['lon'];
        $result[$item['place']]['schools'][] = $item['pname'];
    }
}

print_r($result);

Which should output 哪个应该输出

 Array (
     [Berlin] => Array
     (
         [lat] => 52.519
         [lon] => 13.406
         [schools] => Array
             (
                 [0] => Firstschool
                 [1] => Secondschool
             )

     )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM