I am working within a foreach loop and PARTS my code looks like this:
foreach ($query->rows as $row) {
$myarray = explode(",",$row['text']);
print_r($myarray);
}
The Output result of the above is this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Natural Gas
[3] = Combo
)
Array
(
[0] = coal
)
Array
(
[0] = Natural Gas
[1] = Wood
)
Yes I see there are similar questions to this. But none of their answers seem to work for me. I'm thinking it might be because I am working inside an foreach loop. Either way, I was wondering if there was a way to get my output above to look like this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Propane
)
Array
(
[0] = Coal
)
Array
(
[0] = wood
)
All the duplicates gone, without loosing the formatting of this array. Code I have tried.. but "maybe" wrong was:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
EDIT for Sharanya Dutta:
I have alot of other code, but basically this is where Im trying to use it.
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
$output[$row['attribute_id']]['values'][] = $diff; // <--- USE IT HERE
}
Use an array ($arr in the following code) to store the values and print_r only those values which are different from the already stored values:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
}
DEMO
You may even use $diff after the last line in the foreach loop:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
$arr = array_merge($arr, $_arr);
if($diff !== array()) print_r($diff);
}
DEMO
As you iterate the result set rows and explode the text string, filter the individual values in the current row against all values in all previously encountered rows.
If there are any individual values encountered for the first time, then save the unique values of that row as a new row in the result array.
Code: (Demo)
$resultSet = [
['text' => 'Charcoal,Natural Gas,Combo'],
['text' => 'Charcoal,Propane,Combo'],
['text' => 'Charcoal,Propane,Natural Gas,Combo'],
['text' => 'coal'],
['text' => 'Natural Gas,wood'],
];
$result = [];
foreach ($resultSet as $row) {
$clean = array_diff(
explode(',', $row['text']),
...$result
);
if ($clean) {
$result[] = array_values($clean);
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'Charcoal',
1 => 'Natural Gas',
2 => 'Combo',
),
1 =>
array (
0 => 'Propane',
),
2 =>
array (
0 => 'coal',
),
3 =>
array (
0 => 'wood',
),
)
Related
So currently, I have a single array ($array1) that I want to compare with an array ($array2) that I created by retrieving data from the database. Technically speaking, $array2 is multidimensional since I used a while loop with mysqli_fetch_assoc. Is there any way to compare these two arrays with each other? My end goal is to compare these two arrays, and to only remove the data from the single array ($array1) when there is a mismatch. By that, I mean only to remove the data that doesn't match with $array2.
For example:
$array1 = Array ( [0] => cookies [1] => chicken [2] => tesla )
$array2 = Array ( [name] => tesla ) Array ( [name] => bmw ) Array ( [name] => opel )
So in this case, $array2 came from the database, and $array1 is given. So how can I compare these two arrays in order to get this array back: $arraynew = Array ( [0] => tesla )?
Note:
So far I have tried this:
$query = "SELECT name FROM tagsbreedables WHERE idTagCategory = 6";
$result10 = mysqli_query($conn, $query);
if (mysqli_num_rows($result10) > 0) {
while ($row = mysqli_fetch_assoc($result10)) {
$bloem = $datas4['name'] = $row;
print_r($row);
$subarray = array_column($bloem,'name');
print_r($array3);
}
}
$aMust = explode(" ", $_GET['q']);
$searchTermBits = array();
foreach ($aMust as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "$term";
}
}
$matches = $searchTermBits;
$test = array($subarray, $matches);
foreach ($test as $key => $subarray) {
foreach ($subarray as $subsubarray) {
foreach ($matches as $match) {
if ($subsubarray == $match) {
$finalarr[$key][] = $subsubarray;
}
}
}
}
print_r($finalarr[0]);
$pindakaas = implode('","',$finalarr[0]);
echo $pindakaas;
The code works great, it's just that I don't know how to get data from the database into $subarray... I just get Array ( ) Array ( ) ...for $array3
if $array2 is an array of arrays like below
array(Array ( [name] => tesla ) Array ( [name] => bmw ) Array ( [name] => opel ))
you can use the function array_column to get the values from a single column, in this case name.
$array3 = array_column($array2,'name')
the above should give you
array(0=>tesla,1=>bmw,2=>opel)
you can then use array_intersect to compare them
$arraynew = array_intersect($array1,$array3);
I have this php array named $ids:
Array (
[0] => Array ( [id] => 10101101 )
[1] => Array ( [id] => 18581768 )
[2] => Array ( [id] => 55533322 )
[3] => Array ( [id] => 55533322 )
[4] => Array ( [id] => 64621412 )
)
And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.
Something like this:
$newArr = array(
10101101 => 1,
18581768 => 1,
55533322 => 2,
64621412 => 1,
);
This is what I have:
$newArr = array();
$aux1 = "";
//$arr is the original array
for($i=0; $i<count($arr); $i++){
$val = $arr[$i]["id"];
if($val != $aux1){
$newArr[$val] = count(array_keys($arr, $val));
$aux1 = $val;
}
}
I supose array_keys doesn't work here because $arr has the id values in the second dimension.
So, how can I make this work?
Sorry for my bad english and thanks.
array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.
$newArr = array_count_values(array_column($ids, 'id'));
Or do it by hand like this where $arr is your source array and $sums is your result array.
$sums = array();
foreach($arr as $vv){
$v = $vv["id"];
If(!array_key_exists($v,$sums){
$sums[$v] = 0;
}
$sums[$v]++;
}
You can traverse your array, and sum the id appearance, live demo.
$counts = [];
foreach($array as $v)
{
#$counts[$v['id']] += 1;
}
print_r($counts);
I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.
I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));
I have some php arrays from a loop, all of them bearing the same name. Now I want to merge them, but it seems not to work...
Here's my loop:
while($row = mysql_fetch_row($sql1)){
$startzeit=strtotime($row[2]);
$endzeit=strtotime($row[3]);
$startzeit_format = date("Y-m-d",$startzeit);
$endzeit_format = date("Y-m-d",$endzeit);
$datearray[] = createDateRangeArray($startzeit_format,$endzeit_format);
}
This should be the merging code:
for($i = 0; $i<count($datearray); $i++)
{
$datesarray = array_merge($datearray[$i]);
}
Anyway, the manual merge works fine:
$datesarray = array_merge( $datearray[0], $datearray[1], $datearray[2], $datearray[3]);
This one leads to the desired output. However I'd like to automatize it, as the single arrays come from a database and I won't add a $datearray[4], $datearray[5] and so on, everytime there is a new entry in the mySQL..
The result of print_r($datearray):
Array (
[0] => Array ( [0] => 2014-03-08 )
[1] => Array ( [0] => 2013-09-15 )
[2] => Array ( [0] => 2013-09-21 )
[3] => Array ( [0] => 2013-10-03
[1] => 2013-10-04
[2] => 2013-10-05
[3] => 2013-10-06 )
)
What you might be looking for is to flatten the array:
$datesarray = call_user_func_array('array_merge', $datearray);
It's identical to how you were manually merging together the array items.
See also: call_user_func_array()
You could also do this inside the loop with a simple loop:
$datesarray = array();
while ($row = mysql_fetch_row($sql1)) {
// ...
foreach (createDateRangeArray($startzeit_format,$endzeit_format) as $item) {
$datesarray[] = $item;
}
}
You are merging a single array to nothing.
$newArray = array_merge($array, $array)
Merges those two arrays but you are doing
$array = array_merge($datearray[$i]);
In affect, you are creating an array from one key of an array.