I have following array.
array(5) {
[0]=>
array(1) {
["Cars"]=>
string(5) "Volvo"
}
[1]=>
array(1) {
["Cars"]=>
string(4) "Fiat"
}
[2]=>
array(1) {
["Cars"]=>
string(5) "Volvo"
}
[3]=>
array(1) {
["Cars"]=>
string(8) "Mercedes"
}
[4]=>
array(1) {
["Cars"]=>
string(5) "Volvo"
}
I need to count all Duplicates and create a new array where i have the name of each group and the number how many duplicates there are. Could someone help me with a simple solution?
Find all values of Carswith array_column(), and count their values with array_count_values().
$array = array(
['Cars' => 'Volvo'],
['Cars' => 'Fiat'],
['Cars' => 'Volvo'],
['Cars' => 'Mercedes'],
['Cars' => 'Volvo'],
);
print_r(array_count_values(array_column($array, "Cars")));
Outputs
Array (
[Volvo] => 3
[Fiat] => 1
[Mercedes] => 1
)
Live demo at https://3v4l.org/1jhmh
Related
I am trying to group an array by sport. It could be n number of sports. Finally, then create a new array with it. Is there an efficient way to this without going overkill?
$sports = [
['sport' => 'soccer', 'id' => 97487];
['sport' => 'soccer', 'id' => 244800];
['sport' => 'soccer', 'id' => 258740];
['sport' => 'basketball', 'id' => 147884];
['sport' => 'baseball', 'id' => 222240];
['sport' => 'baseball', 'id' => 222245];
];
Initial array:
array(6) {
[0]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(97487)
}
[1]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(244800)
}
[2]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(258740)
}
[3]=>
array(2) {
["sport"]=>
string(10) "basketball"
["id"]=>
int(147884)
}
[4]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222240)
}
[5]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222245)
}
}
Desired results:
array(3)
{
[0]=>
array(3) {
[0]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(97487)
}
[1]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(244800)
}
[2]=>
array(2) {
["sport"]=>
string(6) "soccer"
["id"]=>
int(258740)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["sport"]=>
string(10) "basketball"
["id"]=>
int(147884)
}
}
[2]=>
array(2) {
[0]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222240)
}
[1]=>
array(2) {
["sport"]=>
string(8) "baseball"
["id"]=>
int(222245)
}
}
}
You can group the array like so:
$sports = [
['sport' => 'soccer', 'id' => 97487],
['sport' => 'soccer', 'id' => 244800],
['sport' => 'soccer', 'id' => 258740],
['sport' => 'basketball', 'id' => 147884],
['sport' => 'baseball', 'id' => 222240],
['sport' => 'baseball', 'id' => 222245]
];
// we will build an array here where the key is the sport
// name and the value is an array of objects pertaining
// to that sport i.e. 'basketball' => [bb1, bb2, ...]
$array = array();
// now consider every sport object in your original array
foreach($sports as $key => $item)
{
if (array_key_exists($item['sport'], $array)) {
// we encountered this same sport in the past so we
// know $array['sportName'] already exists and can
// push right to it
$array[$item['sport']][] = $item;
} else {
// we have never seen this sport before and now must
// insert the sport into $array['sportName'] = []
// and push this sport object to it
$array[$item['sport']] = [$item];
}
}
// since $array's keys are the names of the sports themselves, but
// you want the keys to be numeric, this will build a new array
// from just the values of $array which at this point contains
// grouped arrays of sport objects
$result = array_values($array);
// print the results for good measure :)
print_r($result);
This works by looping over your sports array and building a second array of [sportName => arrayOfThatSport]. Inside the for loop, we are checking to see if a given sport already exists in this array. If it does, great, add the sport to the corresponding array for that sport. Otherwise, create a new array for that sport available at $array['sportName'] = [sportObject]. If you consider several iterations of the loop you will see that we're either always adding to an existing $array['sportName'] array, or creating a new array at this position whenever we encounter a new sport we've never seen before. This gives us a final array similar to: [ "sport
: [...], "sport2": [...] ] but in your case you want a numeric array not an associative array, hence the call to array_values.
This is my suggested solution.
$groupedSports = [];
foreach ($sports as $item) {
if (empty($groupedSports[$item['sport']])) {
$groupedSports[$item['sport']] = [];
}
$groupedSports[$item['sport']][] = $item;
}
Short explanation:
line 1: we initialize an empty array
line 2: we start a loop on the original array
line 3-5: if it's the first occurrence for the current sport, we initialize an empty array for that sport (avoid warnings)
line 6: we assign current item to the appropriate array
I have a big array which looks like this:
array(2) {
["Final Fantasy VII"]=>
array(5) {
["rows"]=>
array(2) {
[0]=>
array(6) {
["price"]=>
string(5) "11.69"
["price_old"]=>
string(4) "4.66"
["currency"]=>
string(4) "euro"
["portal"]=>
string(0) ""
["link"]=>
string(77) "https://de.gamesplanet.com/game/final-fantasy-vii-download--1001-1?ref=gmkeys"
["shop"]=>
string(4) "9507"
}
[1]=>
array(6) {
["price"]=>
string(5) "14.99"
["price_old"]=>
...
}
}
}
["Battlefield 1"]=>
array(3) {
["rows"]=>
array(2) {
[0]=>
array(6) {
["price"]=>
...
}
[1]=>
array(6) {
["price"]=>
...
}
}
}
}
And I want to get only certain parts of this array where the name is matching my searched title. So, I use this code for that:
function createACFRepeater($title){
$repeater = array();
if(searchForGameXML($title)){
$count = count($GLOBALS["productsXML"][$title]['rows']);
for($i = 0; $i < $count; $i++){
array_push($repeater, $GLOBALS["productsXML"][$title]['rows'][$i]);
}
return $repeater;
}else{
return $repeater;
}
}
My problem now is that the the $repeater array looks like this:
array(2) {
[0]=>
array(6) {
["price"]=>
string(5) "19.98"
["price_old"]=>
...
}
[1]=>
array(6) {
["price"]=>
string(4) "7.99"
["price_old"]=>
...
}
}
There is a numeric key which is pointing to the array [0] => .... But what I want is simply an array in a array without any associative relations...
How can I create an array which looks like this:?
array(2) {
array(6) {
["price"]=>
string(5) "19.98"
["price_old"]=>
...
}
array(6) {
["price"]=>
string(4) "7.99"
["price_old"]=>
...
}
}
Greetings and Thank You!
According to the array definition it is impossible. Any array item must have key and value, documentation for array starts from:
An array in PHP is actually an ordered map. A map is a type that associates values to keys
You will always have numeric keys. As #lubart already said: it's impossible to have an array without keys. Btw., all of the the follwing arrays are completely equal:
$array1 = array([0] => array([0] => 'hi', [1] => array([0] => '23.5')));
$array2 = array(array('hi', array('23.5')));
$array3 = [['hi', ['23.5']]];
$array4 = [ [0] => [ [0] => 'hi', [1] => [ [0] => '23.5' ] ] ];
Data is coming from 2 differents SQL request, so i have 2 arrays like :
FIRST ARRAY
array(6) {
[0]=>
array(2) {
["edible"]=>
string(3) "600"
["Food"]=>
string(4) "Fruit"
}
[1]=>
array(2) {
["edible"]=>
string(3) "500"
["Food"]=>
string(6) "Vegetables"
}
[2]=>
array(2) {
["edible"]=>
string(4) "1000"
["Food"]=>
string(3) "meat"
}
...
SECOND ARRAY
array(5) {
[0]=>
array(2) {
["out-of-date"]=>
string(3) "17"
["Food"]=>
string(4) "Fruit"
}
[1]=>
array(2) {
["out-of-date"]=>
string(3) "54"
["Food"]=>
string(3) "Vegetables"
}
[2]=>
array(2) {
["out-of-date"]=>
string(2) "60"
["Food"]=>
string(3) "meat"
}
...
What i would like is to merge the two arrays, but not with a function like array_merge or array_merge_recursive.
Because i would like to just add a row (key + value) like
["out-of-date"]=>
string(3) "17""
in the first array if we have the same Food (key)
output result desired :
array(6) {
[0]=>
array(3) {
["out-of-date"]=>
string(3) "17"
["edible"]=>
string(3) "600"
["Food"]=>
string(4) "Fruit"
}
...
You need to make a loop inside loop and verify the food key, if is equal merge the values to another array, Try this code:
<?php
$array1 = array();
$array1[] = array('food' => 'Fruit', 'edible' => '600');
$array1[] = array('food' => 'Vegetables', 'edible' => '500');
$array1[] = array('food' => 'meat', 'edible' => '700');
$array2 = array();
$array2[] = array('food' => 'Fruit', 'out-of-date' => '17');
$array2[] = array('food' => 'Vegetables', 'out-of-date' => '15');
$array_merged = array();
foreach ($array1 as $key => $value) {
$array_merged[$key] = $value;
foreach ($array2 as $ke => $val) {
if ($val['food'] == $value['food']) {
$array_merged[$key]['out-of-date'] = $val['out-of-date'];
}
}
}
print_r($array_merged);
I'm not sure about structure of your database table. But let's you have two tables in your MySql database:
First - edible | Food
Second - out_of_date | Food
So you can query your array by using join mysql operation. You need sql like below:
SELECT *
FROM First
LEFT JOIN Second ON First.Food=Second.Food
Also, you can use additional conditions for all tables like:
SELECT *
FROM First
LEFT JOIN Second ON First.Food=Second.Food
WHERE First.edible = 1000 AND Second.out_of_date = 10
You can find more information here: http://dev.mysql.com/doc/refman/5.7/en/join.html
I have 2 arrays. Sometimes a key/value from array1 may equals to key/value of array2. If that is true, change 'status' from the specific key/value from array2, to a new value. Does that make sense?
Here is where I am at:
foreach($array1 as $i=>$x){
foreach($array2 as $k=>$y){
if($x['url'] == $y['url']){
// Up to here works
foreach($i as &$value) {
$value['status'] = 'new value';
}
break;
}
}
}
This are my arrays:
array(1) {
[0]=> array(1) {
["url"]=> string(104) "aHR0cDovL3lvdXR1YmUuY29t"
["date"]=> string(19) "2014-01-06 21:44:39"
["status"]=> string(1) "0"
}
[1]=> array(1) {
["url"]=> string(28) "d3d3LnR3aXR0ZXIuY29t"
["date"]=> string(19) "2014-01-06 14:28:32"
["status"]=> string(1) "0"
}
}
and array2:
array(2) {
[0]=> array(2) {
["url"]=> string(104) "aHR0cDovL3lvdXR1YmUuY29t"
["date"]=> string(19) "2014-01-06 21:44:39"
}
[1]=> array(2) {
["url"]=> string(28) "aHR0cDovL3d3dy5nb29nbGUuY29t"
["date"]=> string(19) "2014-01-06 14:28:32"
}
}
Up to the comment it works. From there after, how can I change that specific key/value to a new value? My current example changes all key 'status' to 'new value'.
You don't have to loop again through array1 just change the key of it
$array1[$i]['status'] = 'new value';
How about this:
<?php
$array1 = array(
array(
"url" => "aHR0cDovL3lvdXR1YmUuY29t",
"date" => "2014-01-06 21:44:39",
"status" => "0"
)
);
$array2 = array(
array(
"url" => "aHR0cDovL3lvdXR1YmUuY29t",
"date" => "2014-01-06 21:44:39",
)
);
array_walk($array2, function($arr2) use (&$array1)
{
foreach($array1 as &$arr1)
{
if($arr2['url'] == $arr1['url'])
$arr1['status'] = "something";
}
});
print_r($array1);
Output:
Array
(
[0] => Array
(
[url] => aHR0cDovL3lvdXR1YmUuY29t
[date] => 2014-01-06 21:44:39
[status] => something
)
)
update, solved
I have the following 2 array's (with the same length), I want to display these values in a table. The problem is he prints just my first array ($gPositionStudents) and not the values of array $gPositionInternships.
The goal is to link each student to a different internship, but I know there is no relationship between these two array's. I'm looking for a function that can shift these 2 array's so that each time I shift the student has a other internship.
Importend to know, I did a small modification on array $gStartPositionInternship, I made this array equal in size as the length of array $gStartPositionStudents. With following code:
enter code here// Make items in $gStartPositionInternships as long as array $gStartPositionStudents
$gStartPositionInternships = array_pad($internships, $lengthStudentArray, 'null');
I included my current output, see image:
enter code here// Make table
$header = array();
$header[] = array('data' => 'Internship');
$header[] = array('data' => 'UGentID');
// this big array will contains all rows
// global variables.
global $gStartPositionStudents;
global $gStartPositionInternships;
$rows = array();
foreach($gStartPositionStudents as $value) {
foreach($gStartPositionInternships as $key=>$value2) {
// each loop will add a row here.
$row = array();
// build the row
$row[] = array('data' => $value[0]['value']);
$row[] = array('data' => $value2);
}
// add the row to the "big row data (contains all rows)
$rows[] = array('data' => $row);
}
$output = theme('table', $header, $rows);
return $output;
var_dump of $gPositionStudents
array(148) {
[0]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "804868"
}
}
[1]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "804869"
}
}
[2]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "705169"
}
}
[3]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "805148"
}
}
[4]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "702342"
}
}
[5]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "803176"
}
}
[6]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "706651"
}
}
[7]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "706333"
}
}
[8]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "806026"
}
}
[9]=>
array(1) {
[0]=>
array(1) {
["value"]=>
string(6) "702808"
}
}
var_dump of: $gPositionInternships
array(148) {
[0]=>
string(18) "Pcv (campus Aalst)"
[1]=>
string(53) "Mss ( Privaatpraktijk kinesitherapie Walravens Marc )"
[2]=>
string(54) "Mss ( Privaatpraktijk kinesitherapie Peeters Stefaan )"
[3]=>
string(35) "psychiatrie (campus Vercruysselaan)"
[4]=>
string(39) "interne geneeskunde (campus Loofstraat)"
[5]=>
string(40) "interne geneeskunde (campus Kennedylaan)"
[6]=>
string(29) "heelkunde (campus Loofstraat)"
[7]=>
string(30) "heelkunde (campus Kennedylaan)"
[8]=>
string(33) "heelkunde (campus Vercruysselaan)"
[9]=>
string(38) "logopedie (groepspraktijk Logomatopee)"
[10]=>
string(41) "logopedie (Koninklijk Instituut Spermali)"
[11]=>
string(34) "Fysieke activiteit (To Walk Again)"
[12]=>
string(53) "algemene en plastische heelkunde ( AZ AZ Oudenaarde )"
[13]=>
string(38) "dermatologie (campus Maria Middelares)"
[14]=>
string(29) "NKO (campus Maria Middelares)"
[15]=>
string(38) "dermatologie (campus Maria Middelares)"
[16]=>
string(38) "Fysieke activiteit (Beweegkamp Vlabus)"
[17]=>
string(43) "Hoofdverpleegkundige ( UZ UZ Gent Urologie)"
[18]=>
string(66) "Opleidingscoördinator ( Onderwijsinstelling Arteveldehogeschool )"
[19]=>
string(90) "Verpleegkundig Specialist ( UMC Universitair Medisch Centrum Universitair Medisch Centrum)"
[20]=>
string(31) "Mss ( AZ Nikolaas campus Hamme)"
[21]=>
string(74) "Mss ( Privaatpraktijk kinesitherapie Cuigniez Pascale PR Cuigniez Pascale)"
$rows[] assignment is inside the nested loop - it looks suspicious to me. Try to put that assignment after the nested loop, like this:
foreach($studentUGentID as $key=>$value) {
foreach($internshipNaam as $key2=>$value2) {
...
}
// add the row to the "big row data (contains all rows)
$rows[] = array('data' => $row);
}
Are your original arrays populated as expected ? Try print_f to figure it out. As far as I see if your original arrays have both 2 entries you should get a 4 entries array with like :
$rows = array(
[0] => array(
'data' => array(
[0] => array(
'data' => value
),
[1] => array(
'data' => value
)
),
[1] => array(
'data' => array(
[0] => array(
'data' => value
),
[1] => array(
'data' => value
)
),
[2] => array(
'data' => array(
[0] => array(
'data' => value
),
[1] => array(
'data' => value
)
),
[3] => array(
'data' => array(
[0] => array(
'data' => value
),
[1] => array(
'data' => value
)
)
)
)
is that really what you expect ?