douyinmian8151 2015-03-14 08:30
浏览 31
已采纳

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

I need to create a new array from an existing one, choose from an array of all the old data that coincide in one field and bring it into the new array, given that the name was one and the necessary data are collected together.

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 to sort

$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"));

Loop

$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>";
        }
    }
}}

New array

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

1条回答 默认 最新

  • douzhi9395 2015-03-14 08:44
    关注

    You can do a single loop through and be a lot more efficient. Use an associative array instead of a normal index to make it easy to identify.

    # $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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100