This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 8 years ago.
This the array...
$rt = array(
'0' => array(
'nombre'=>'Jojo',
'fecah'=> '195',
'fch'=>'12'
),
'1' => array(
'nombre'=>'Tito',
'fecah'=> '197',
'fch'=>'13'
),
'2' => array(
'nombre'=>'Jojo',
'fecah'=> '195',
'fch'=>'12'
),
'3' => array(
'nombre'=>'Joji',
'fecah'=> '195',
'fch'=>'12'
),
);
and this is my code:
$a = array();
foreach ($rt as $k=>$v) {
if (in_array($v['nombre'], $a) && in_array($v['fecah'], $a) && in_array($v['fch'], $a) ) {
$a[]=$k;
echo 'The name ' . $v['nombre'] .' is in the array<br>';
} else {
echo 'The name is not in the array <br>';
}
}
so as you can see in the array index [2] the information also exist in the index [0], so I don't need it again, so I need a away to see if the data get repeated or not... if the data is "unique" then build the new array with the "unique" data if the data already exist then jump to next, but I need to compare the 3 keys not just the name... so how do I do that?
You insert array when it is in_array and you use AND
you should reverse your codes like this
$a = array();
foreach ($rt as $k=>$v) {
if (!in_array($v['nombre'], $a) || !in_array($v['fecah'], $a) || !in_array($v['fch'], $a) ) {
$a[]=$k;
echo 'The name ' . $v['nombre'] .' is in the array<br>';
} else {
echo 'The name is not in the array <br>';
}
}
This is you need this
$newarray = array();
foreach($rt as $key => $value)
{
$nombre = $value['nombre'];
if(!isset($newarray[$nombre]))
{
$newarray[$nombre] = $value;
}
}
Related
I am trying to find a way to extract the changes between two arrays with the same structure.
Both are arrays of subarray associatives
The associative pieces always have a key that is the key to finding
the differences
The differences can be modifications to a subarray, a new subarray or
the elimination of a subarray
Before the comparison the array was ordered using as a value to order, the key 'name'
Data contains all scenarios used in testing
private function getValuesItem(array $array): string
{
$string = '';
foreach ($array as $clave => $valor) {
$string .= $clave . ': ' . $this->setTypeToString($valor) .'<br /> ';
}
return $string;
}
$oldjson = "[{"name":"column1","type":"boolean","length":255},{"name":"column2","type":"integer","length":10},{"name":"column3","type":"boolean","length":100},{"name":"column4","type":"integer","length":255},{"name":"column5","type":"string","length":100}]";
$newjson = "[{"name":"column1","type":"boolean","length":255},{"name":"column2","type":"integer","length":10},{"name":"column3","type":"boolean","length":100},{"name":"column4","type":"integer","length":255},{"name":"column5","type":"string","length":100}]"
$differences = array();
$newer = json_decode($newjson, true);
$older = json_decode($oldjson, true);
foreach ($newer as $new) {
foreach ($older as $old) {
// Modifications
if ($new['name'] === $old['name']) {
foreach ($new as $clave => $valor) {
if ($old[$clave] != $new[$clave]) {
$differences[] = [
'type' => 'Modified',
'name' => $new['name'],
'old' => $this->setTypeToString($old[$clave]),
'new' => $this->setTypeToString($new[$clave])
];
}
}
continue;
} else {
// Added
if ($new['name'] !== $old['name']) {
dd($new['name'],$old['name']);
$differences[] = [
'type' => 'Added',
'name' => $new['name'],
'old' => '',
'new' => $this->getValuesItem($new)
];
break 2;
}
}
}
}
But I got stuck and I am unable to do it. When I create new unit tests, adding or modifying some of the possibilities something goes wrong.
This question already has answers here:
How to GROUP BY and SUM PHP Array? [duplicate]
(2 answers)
Closed 9 months ago.
I want to sum subarray values and group by a subarray value but I am getting error: 'Undefined index: EEReg'.
The array is as follows.
and the current code is;
$total_balances = array();
foreach ($balances as $balance) {
foreach ($balance as $key => $value) {
if ($key == 'MemberNumber' || $key == 'Portfolio') {
continue;
} else {
$total_balances[$balance['Portfolio']][$key] += $value;
}
}
}
I expect the result to be;
$total_balances = [
"Aggressive" => [
"EEReg" => "Sum of EEReg where Portfolio is Aggressive",
"ERReg" => "Sum of ERReg where Portfolio is Aggressive",
],
"Moderate" => [
"EEReg" => "Sum of EEReg where Portfolio is Moderate",
"ERReg" => "Sum of ERReg where Portfolio is Moderate",
]
]
You need to use foreach only once and also you need to define the keys in $total_balance array before using them. Please see below code
$total_balances = array();
foreach ($balances as $balance) {
if( !isset( $total_balances[$balance['Portfolio']] )) {
$total_balances[$balance['Portfolio']] = array('EEREG' => 0, 'ERREG' => 0);
}
$total_balances[$balance['Portfolio']]['EEREG'] += $balance['EEREG'];
$total_balances[$balance['Portfolio']]['ERREG'] += $balance['ERREG'];
}
This question already has answers here:
How to check if a specific value exists at a specific key in any subarray of a multidimensional array?
(17 answers)
Closed 3 years ago.
I have an array that looks like this:
$array = array(
array('name' => 'number1', 'number' => '0612345675'),
array('name' => 'number2', 'number' => '0634345675'),
array('name' => 'number3', 'number' => '0634378675')
);
Now I have this number: 0634345675.
How can I check If this number exists in the array $array?
I tried to do this:
if(!in_array('0634345675', $array)){
// insert into DB
}
But this keeps adding multiple of the same rows.
Does anyone knows how to check if this number exists in $array?
Full code:
foreach($DN as $number){ // $DN got ['0634345675', '0632545675', '0614342375']
if(!in_array($number, $array)){
// insert into DB
}
}
You have to use in_array() along with array_column()
<?php
$array = array(
array('name' => 'number1', 'number' => '0612345675'),
array('name' => 'number2', 'number' => '0634345675'),
array('name' => 'number3', 'number' => '0634378675')
);
$valueToFind = '0634345675';
if (in_array($valueToFind, array_column($array, 'number'))){
echo 'found';
}else{
echo 'not found';
}
Output:- https://3v4l.org/TUtSL
If you want to show that array too, then use array_search()
$key = array_search($valueToFind, array_column($array, 'number'));
if($key){
echo 'value found';
echo PHP_EOL;
echo "matched array is";
echo PHP_EOL;
print_r($array[$key]);
}
Output:-https://3v4l.org/Mc2cC
In case multiple match found:
$valueToFind = '0634378675';
$matchedArray = array();
foreach($array as $arr){
if($valueToFind == $arr['number']){
$matchedArray[] = $arr;
}
}
if( count($matchedArray) > 0){
echo "match found";
echo PHP_EOL;
print_r($matchedArray);
}
Output:- https://3v4l.org/p439T
This question already has answers here:
Delete element from multidimensional-array based on value
(7 answers)
Closed 5 years ago.
foreach ($array_leave_dates as $emp => $leave_type) {
foreach ($leave_type as $leave_dates) {
if($leave_type == 'Maternity Leave'){
unset($array_leave_dates[$leave_type]);
}
else{
echo $leave_dates[$row];
}
}
}
Here we can fetch $leave_dates and want to remove or unset leave_type == 'Maternity Leave'. But could'nt. Please help to point out the mistake in my code above.
Have a look at the // comments
foreach ($array_leave_dates as $emp => $leave_type) {
// you treat $leave_type as array here
foreach ($leave_type as $leave_dates) {
// you treat $leave_type as string here
// doesn't feel right
if($leave_type == 'Maternity Leave') {
// you are unsetting with a value
//unset($array_leave_dates[ --> $leave_type <-- ]);
// i assume you want to delete the key
unset($array_leave_dates[$emp]);
}
else{
// $row doesn't seem to exist, looks wrong from here
echo $leave_dates[$row];
}
}
}
Not sure what your data source looks like:
<?php
// Remove the whole employee
$employees = array(
'emp1' => array('sick' => 'Mon - Tue'),
'emp2' => array('bun in oven' => '2016 - 2017'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp]);
}
}
}
print_r($employees);
// OR remove only 'Maternity' from the employee but keep everything else
<?php
$employees = array(
'emp1' => array('sick' => 'Mon - Tue', 'its friday and im not coming in' => 'Fri'),
'emp2' => array('bun in oven' => '2016 - 2017', 'sick' => 'Thu'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp][$leaveName]);
}
}
}
print_r($employees);
If $leave_type can be "Maternity Leave", then why do you search for $leave_dates inside that string value? The question is naturally rethorical. From the very fact that you have two foreach cycles and the second is embedded into the first makes me think that $leave_type is not what you think it is. So, I think you have a multi dimensional array, where the outer keys are employee names or ids and the inner keys are the types. Example:
array(
'John Doe' => array('Sickness' => array('a', 'b', 'c')),
'Mary Doe' => array('Sickness' => array('a', 'b', 'c'), 'Maternal Leave' => array('d', 'e'))
)
If that is the case, then you need to modify your cycles:
foreach ($array_leave_dates as $emp => $leave) {
if ($leave['Maternity Leave']) {
unset($array_leave_dates[$emp]['Maternity Leave']);
}
}
If you want a more general solution, then this might help you:
function removeByKey(&$arr, $k) {
if (arr[$k] !== null) {
unset arr[$k];
}
foreach($arr as $key => $value) {
if (is_array($value)) {
$arr[$key] = removeByKey($arr[$key], $k);
}
}
return $arr;
}
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I have an array of arrays in PHP that I created like the following:
$wp_players = array();
while ($wp_player = mysql_fetch_array($wp_player_query))
{
$wp_player_ranking = mysql_query(get_ranking_sql($wp_player['id'])) or die(mysql_error());
$wp_ranking = mysql_fetch_array($wp_player_ranking);
array_push($wp_players, array('first_name' => $wp_player['first_name'],
'last_name' => $wp_player['last_name'],
'school_name' => $wp_player['school_name'],
'1st' => $wp_ranking['1st'],
'2nd' => $wp_ranking['2nd'],
'3rd' => $wp_ranking['3rd'],
'4th' => $wp_ranking['4th'],
'5th' => $wp_ranking['5th'],
'total' => ($wp_ranking['1st'] + $wp_ranking['2nd'] + $wp_ranking['3rd'] + $wp_ranking['4th'] + $wp_ranking['5th'])));
}
What I want to do now is have $wp_players array sorted by the 'total' key that's inside each of its elements. Since the Array is not flat, and is an array of arrays, what's the best way to do this in PHP?
array_multisort() will accomplish precisely what you're looking to achieve:
$totals = array();
foreach ($wp_players as $key => $row) {
$totals[$key] = $row['total'];
}
array_multisort($totals, SORT_DESC, $wp_players);
This function will be what you want, this function if from my development framework, It suits for many situations, has order control and reserveKey control parameters.
<?php
function sortByField($arr, $fieldName, $flag = 'desc', $reserveKey = true)
{
$indexArr = array();
foreach ($arr as $idx => $item)
{
$indexArr[$idx] = $item[$fieldName];
}
if ('desc' == $flag)
{
arsort($indexArr);
}
else
{
asort($indexArr);
}
$result = array();
foreach ($indexArr as $idx => $field)
{
if($reserveKey)
{
$result[$idx] = $arr[$idx];
}
else
{
$result[] = $arr[$idx];
}
}
return $result;
}
usage
$wp_players = sortByField($wp_players, 'total');