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",);
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);
}