Below is the code snippet:
$resultArray = explode("\n",$cmd);
print_r($resultArray);
$tempArray = array();
foreach($resultArray as $key){
$tempArray = explode(" ",$key);
print_r($tempArray);
}
first print gives output:-
Array
(
[0] => AA-BB-E3-1B-81-6A 10.10.10.2
[1] => CC-DD-E3-1B-7E-5A 10.10.10.3
)
Second print gives output:-
Array
(
[0] => AA-BB-E3-1B-81-6A
[1] => 10.10.10.2
)
Array
(
[0] => CC-DD-E3-1B-7E-5A
[1] => 10.10.10.3
)
Array
(
[0] =>
)
Assuming there will be many entries of mac addresses corresponding mac addresses, I want to store them in separate variables for further use.
Please help. I am new to PHP, learning on my own. Any help is appreciated.
eidt 1: Expected output should be two arrays, one each for mac address and Ip Address from which I would be able to loop through and query database for each mac address.
Well I'm not sure what you want to do, but from the little I understood is to separate the mac addresses:
$resultArray = explode("\n", $cmd);
print_r($resultArray);
$tempArray = array();
foreach($resultArray as $key){
$dm = explode(" ", $key);
$tempArray[] = $dm[0];
}
print_r($tempArray);
The result would be:
Array
(
[0] => AA-BB-E3-1B-81-6A
[1] => CC-DD-E3-1B-7E-5A
.
.
.
)
It would be much better if you put the expected result, in order to help you better.
You forget [] for tempArray :
$resultArray = explode("\n",$cmd);
print_r($resultArray);
$tempArray = array();
foreach($resultArray as $key){
$tempArray[] = explode(" ",$key);
print_r($tempArray);
}
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);
How can I delete duplicates from multiple arrays?
pinky and cocos are double in my array. All words which are double, must be removed. If those are removed, I will put these words in my select.
I get those words from my database.
The query:
$queryClient = " SELECT DISTINCT `clients` FROM `reps` WHERE `clients` != ''";
This is my code:
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['clients']);
echo '<pre>'; print_r($names); echo '</pre>';
}
Result: (Those food words are just an example)
Array
(
[0] => chocolate
)
Array
(
[0] => vanilla
[0] => cocos
)
Array
(
[0] => strawberry
)
Array
(
[0] => pinky
[1] => watermelon
[2] => melon
[3] => cocos
)
Array
(
[0] => pinky
)
Array
(
[0] => dark-chocolate
)
I tried this in my while loop but it did not work:
$array = array_unique($names, SORT_REGULAR);
How can I remove all duplicates? Can you help me or do you have a solution for my problem? Help.
Here's a one-liner:
print_r(array_unique(call_user_func_array('array_merge', $names)));
First merge all subarrays into one, then get unique values.
Full example:
$names = array();
while($row = mysql_fetch_assoc($resultClient)){
$names[] = explode(",", $row['clients']);
}
print_r(array_unique(call_user_func_array('array_merge', $names)));
You can just do a little trick:
Flatten, count and then remove all except the last.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flatArray = [];
foreach($it as $v) {
$flatArray[] = $v; //Flatten array
}
//Note you can do array_unique on the flat array if you also need to flatten the array
$counts = array_count_values($flatArray); //Count
foreach ($array as &$subarray) {
foreach ($subarray as $index => $element) {
$counts[$element]--;
if ($counts[$element] > 0) { //If there's more than 1 left remove it
unset($subarray[$index]);
}
}
}
This will remove duplicates nested exactly on the 2nd level without flattening the original array.
http://sandbox.onlinephpfunctions.com/code/346fd868bc89f484dac48d12575d678f3cb53626
first you need to join your array before you can filter out the duplicates:
<?php
$allNames = [];
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['food']);
$allNames[] = $names;
}
$allNames = array_merge(...$allNames); //Join everything to a one dimensional array
$allNames = array_unique($allNames); // Only keep unique elementes
print_r($allNames);
I'm little bit confuse in this concept
Actually I'm having an array like this
$arr = array("0"=>array("username"=>"username1"),"1"=>array("username"=>"username2"),"2"=>array("username"=>"username3"),"3"=>array("username"=>"username4"));
echo "<pre>";print_r($arr);
$finalArray = call_user_func_array('array_merge', $arr);
echo "<pre>";print_r($finalArray);
Finally from this I'm getting an array like this
Array
(
[username] => username4
)
But I need all the values like as follows
Array
(
[0] => username1
[1] => username2
[2] => username3
[3] => username4
)
How should I do this?..Could someone please help me..
Thank you,
Simple solution using array_column function(available since PHP 5.5):
$result = array_column($arr, 'username');
You can write your own function to get usernames
Try this
<?php
function getUserNames($arr){
$userNames = array();
foreach ($arr as $key => $value){
$userNames[$key] = $value["username"];
}
return $userNames;
}
$arr = array("0"=>array("username"=>"username1"),"1"=>array("username"=>"username2"),"2"=>array("username"=>"username3"),"3"=>array("username"=>"username4"));
echo "<pre>";print_r($arr);
$finalArray = getUserNames($arr);
echo "<pre>";print_r($finalArray);
?>
I can't get past making what I think is a 2D Array in PHP. I'm using a CSV as source input and want to take one of the columns and split that into an array as well.
$csv = array_map("str_getcsv", file("data/data.csv", FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);
foreach ($csv as $i => $row) {
$csv[$i] = array_combine($keys, $row);
$linkto = $csv[$i]['linkto'];
// $linktoArray = explode(" ", $linkto);
echo '<pre>';
// print_r($linktoArray);
echo '</pre>';
$csv[$i] = array_combine($keys, $row);
}
$csv['timestamp'] = time();
echo '<pre>';
print_r($csv);
echo '</pre>';
Will output:
Array
(
[0] => Array
(
[color] => 1
[shape] => 0
[label] => string
[size] => 1
[linkto] => 1 2 3
)...
Using something similar to what I commented out, I'd love to see something like:
Array
(
[0] => Array
(
[color] => 1
[shape] => 0
[label] => string
[size] => 1
[linkto] => Array
(
[0]=>1
[1]=>2
[2]=>3
)
)...
However, right now I'm just getting an array before my containing array. Pardon my ignorance, I haven't had much experience past the front-end. Any suggestions? I'm sure this has been explained before, but I can't find the right terminology to utilize a search.
It's fairly straight forward. All you need to do is this:
$linkto = $csv[$i]['linkto'];
$linktoArray = explode(" ", $linkto);
$csv[$i]['linkto'] = $linktoArray;
After having read through your code again, you seem to be struggling with the concept of foreach. When you use foreach you don't access $csv[$i] like you have, you just use $row. Try something like:
//The & symbol means any changes made to $row inside the foreach will apply outside the foreach.
foreach($csv as $i => &$row) {
$row['linkto'] = explode(" ", $row['linkto']);
}
That should be all you need, none of this array_combine stuff.
Here is a modified example from the SplFileObject::fgetcsv documentation that might simplify your code enough to isolate what might be giving you issues:
$file = new SplFileObject("data/data.csv");
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY);
$header_row = ($file->fgetcsv());
foreach ($file as $row) {
$row = array_combine($header_row, $row);
$row['linkto'] = explode(" ", $row['linkto']);
$csv[] = $row;
}
print_r($csv);
I have this array:
$fields = $_GET['r'];
Which has some ids, for example:
Array (
[0] => 3134
[1] => 3135 )
and then I have this string in $tematiche:
3113,3120
How can I marge this string in the first array? Also, how can I remove the equals id (if any)?
Try,
$fields = array_unique(array_merge($fields,explode(",",$tematiche)));
echo "<pre>";
print_r($fields);
Try this :
$fields = $_GET['r'];
$string = '3113,3120';
$array = explode(",",$string);
$res_array = array_unique(array_merge($fields,$array));
echo "<pre>";
print_r($res_array);
Output :
Array (
[0] => 3134
[1] => 3135
[2] => 3113
[3] => 3120
)
A combination of explode(), array_merge() and array_unique() would be suitable.
// Make $tematiche into an array
$tematiche_array = explode(',', $tematiche);
// Merge the two arrays
$merged_array = array_merge($fields, $tematiche_array);
// Remove all duplicate values in the array
$unique_array = array_unique($merged_array);
Please try like this. This should work for you.
$a = explode(',', '3113,3120');
print_r(array_merge($fields,$a));