Compare the new array with the previous one - php

I have an array with 4 elements
[1, 2, 3, 4]
So far I am printing several arrays, all with different elements in each array, to a limit set by me.
for($i = 0; $i<=100; $i++){//...
Output so far:
[11, 22, 32, 44]
[22, 33, 44, 45]
[12, 24, 25, 31]
[15, 16, 31, 41]
[22, 33, 44, 45]//already exist
[11, 22, 32, 44]//already exist
...
How can I compare an outgoing array to the next one going out and delete the new one if is equal to the previous array?

You could create a key for an array with the help of implode() and have a set array which has this key. If key is already present, then the current array in iteration is a duplicate one, else it's a new one. Remember to sort the current array as the order of the numbers matter here for proper key check.
<?php
$arr = [
[11, 22, 32, 44],
[22, 33, 44, 45],
[12, 24, 25, 31],
[15, 16, 31, 41],
[22, 33, 44, 45],
[44, 22, 32, 11]
];
$set = [];
foreach($arr as $curr_array){
sort($curr_array);
$hash = implode("|",$curr_array);
if(isset($set[$hash])) echo "Duplicate",PHP_EOL;
else{
print_r($curr_array);
$set[$hash] = true;
}
}
Demo: https://3v4l.org/EXXRu

Related

how to get same values if an array have values same with values of anther array values in PHP?

Having two arrays of authRoom and partiRoom with one same value inside them. Want to find that same value if it was matched
Found array_search function that work only with single variable
$authRoom = [8, 7, 1, 22, 13, 18, 10];
$partiRoom= [3, 6, 5, 9, 8];
I want the output to be 8 which is the same value of these two arrays
You can use array_intersect which will give you an array of the same values in both $authRoom and $partiRoom like so:
$authRoom = [8, 7, 1, 22, 13, 18, 10];
$partiRoom = [3, 6, 5, 9, 8];
$res = array_intersect($authRoom, $partiRoom);
print_r($res); // [8]
If you want to get the value 8 outside of the array, you can simply access the first value using index 0:
$res = array_intersect($authRoom, $partiRoom)[0];
echo $res; // 8

Laravel 5.8 update mysql json column cast as array changes data stored format

I have a table with a json column cast as array. The Schema creation has the column defined like this:
$table->json('row_ids');
In my class:
protected $casts = [
'row_ids' => 'array',
];
I generate the data in this array / column by getting every row id from another table like this:
$id_array = DB::table($table->name)->pluck('api_id')->toArray();
TableChannelRow::create([
'table_api_id' => $table->api_id,
'channel_api_id' => $channel->api_id,
'row_ids' => $id_array,
]);
When I dd a collection record I can see the columns in the target table OK, with one of the columns containing an array as expected:
#attributes: array:4 [▼
"api_id" => 2
"table_api_id" => 1
"channel_api_id" => 6
"row_ids" => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, ▶"
]
When I check in MySQLWorkbench the data looks like this:
In another controller I want to add or remove entries from the array in this column like this:
$table_channel_row = TableChannelRow::where('table_api_id', '=', $rowId)
->where('channel_api_id', '=', $channelId)
->first();
$row_ids = $table_channel_row->row_ids;
if ($is_checked == 'yes') {
// Add value to array if it does not already exist
if (!in_array($row_id, $row_ids)) {
array_push($row_ids, $row_id);
}
} else {
// Remove value from array
$row_id_array[] = $row_id;
$row_ids = array_diff($row_ids, $row_id_array);
}
$table_channel_row->update([
'row_ids' => $row_ids,
]);
Now the data in MySQLWorkbench looks like this:
Why does it get stored looking like a PHP array in the first instance, then later on update it gets stored as a json object?
Additionally the remove PHP code is working, yet the add is not, though it does not trigger an exception (you can see the first value is removed in the second image, but I cannot find it in the object in MySQL when I trigger the code to add it)
What did I miss? Thanks!
The reason why it's saving differently is because array_diff returns an associative array whereas your initial data is an indexed array. Take the following for example:
$ids = [1, 2, 3, 4, 5];
$ids2 = [1, 2, 3];
Then if you perform an array_diff($ids, $ids2), it would return the following:
[
3 => 4,
4 => 5
]
So if you want to save as the same format as your initial one, you have to retrieve the values of the array using array_values:
$row_ids = array_values(array_diff($row_ids, $row_id_array));

Laravel Eloquent column cast as array, cannot access array

I have a table with a json column cast as array.
In my class:
protected $casts = [
'row_ids' => 'array',
];
I access this column via a relationship in another class:
public function table_rows()
{
return $this->hasMany(TableChannelRow::class, 'channel_api_id', 'api_id');
}
When I dd the relationship I can see the columns in the target table OK, with one of the columns containing an array as expected:
dd($channel->table_rows);
#attributes: array:4 [▼
"api_id" => 2
"table_api_id" => 1
"channel_api_id" => 6
"row_ids" => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, ▶"
]
In my Blade template page I check whether the current record id is in the column array like this:
#foreach($channels as $channel)
#if(in_array($row->api_id, $channel->table_rows->row_ids)) true #endif
#endif
But this fails with:
Property [row_ids] does not exist on this collection instance.
What have I missed? Thanks.
Your table_rows relationship returns a collection. So you have to loop through the collection or grab the first instance in your collection:
$channel->table_rows->first()->row_ids

sort multidimensional array by values in PHP

I have an array fetched from mysql database tables of type. I want to sort it in order of particular value.
$arr1=array(array(12, 8, 5, 34),
array(54, 87, 32, 10),
array(23, 76, 98, 13),
array(53, 16, 24, 19));
How can i sort it by value?
Like sorting by 2nd value should result to.
$arr1=array(array(12, 8, 5, 34),
array(53, 16, 24, 19),
array(23, 76, 98, 13),
array(54, 87, 32, 10));
I like to use usort to solve these problems.
$sortKey = 1;
usort($arr1, function($a, $b) use($sortKey){
return $a[$sortKey] - $b[$sortKey];
});
Got to agree with #RocketHazmat, array_multsort is a royal pain in the backside. usort is much easier to follow but I thought I'd have a go anyway:
$sortKey = 1;
array_multisort(array_map(function($v) use($sortKey){
return $v[$sortKey];
}, $arr1), $arr1);
It only took 20 minutes... :(
Here's a demo: http://ideone.com/2rZYIz

Get max value from each column of a 2-dimensional array

I have an array within an array, for example:
[
[0, 20, 5],
[5, 0, 15],
[5, 10, 0]
]
I need to get the max number in each column.
The max of [0 , 5 , 5] is 5, so that goes into the result array.
The max of [20, 0, 10] is 20, so that goes into the result array.
The max of [5, 15, 0] is 15, so that goes into the result array.
The final result array must contain [5, 20, 15].
First, the array has to be transposed (flip the rows and columns):
function array_transpose($arr) {
$map_args = array_merge(array(NULL), $arr);
return call_user_func_array('array_map', $map_args);
}
(taken from Is there better way to transpose a PHP 2D array? - read that question for an explanation of how it works)
Then, you can map the max function on the new array:
$maxes = array_map('max', array_transpose($arr));
Example: http://codepad.org/3gPExrhO
Output [I think this is what you meant instead of (5, 15, 20) because you said index 1 should be max of (20, 0, 10)]:
Array
(
[0] => 5
[1] => 20
[2] => 15
)
Without the splat operator, array_map() with max() will return the max value for each row. ([20, 15, 10])
With the splat operator to transpose the data structure, the max value for each column is returned.
Code: (Demo)
$array = [
[0, 20, 5],
[5, 0, 15],
[5, 10, 0]
];
var_export(
array_map('max', ...$array)
);
Output:
array (
0 => 5,
1 => 20,
2 => 15,
)

Categories