我需要用php创建和排序新数组

时间:2015-03-14 08:30:55

标签: php arrays sorting

我需要从现有数组创建一个新数组,从一个字段中重合的所有旧数据的数组中选择并将其带入新数组中,因为名称为1并且必要的数据一起收集

class Data{
public $name;
public $city;
public $country;
public $partnername;

public function __construct($name, $city, $country, $partnername)
{
    $this->name = $name;
    $this->city = $city;
    $this->country = $country;
    $this->partnername = $partnername;
}}

要排序的数组

$array = array(
new Data("Serghio", "Madrid", "Spain", "C#"),
new Data("John", "London", "England", "PHP"),
new Data("Ivan", "Moscow", "Russia", "C++"),
new Data("John", "London", "England", "C++"),
new Data("Smith", "Milan", "Italy", "PHP"),
new Data("John", "London", "England", "Java"));

循环

$isVisited = array(count($array));
for($i = 0; $i < count($array); $i++){
  $isVisited[$i] = true;
  for($j = 0; $j < count($array); $j++){
    if($i != $j && @!$isVisited[$j]) {
        $isVisited[$j] = true;
        if($array[$i]->name == $array[$j]->name) {
            print_r($array[$j]);
            echo "<br>";
        }
    }
}}

新数组

$newarray = array(
"Serghio", "Madrid", "Spain", "C#",
"John", "London", "England", "PHP", "C++", "Java",
"Ivan", "Moscow", "Russia", "C++",   
"Smith", "Milan", "Italy", "PHP",);

1 个答案:

答案 0 :(得分:0)

您可以执行单循环并提高效率。使用关联数组而不是普通索引,以便于识别。

# $isVisited = array(count($array)); // This does not do what you think it does
for($i = 0; $i < count($array); $i++){
    if (!isset($newarray[$array[$i]->name]))
        $newarray[$array[$i]->name] = array($array[$i]->city, $array[$i]->country, $array[$i]->partnername);
    else
        array_push($newarray[$array[$i]->name], $array[$i]->partnername);
}