I am trying to create an array that holds the count of each course we offer based on location and then instructor. Here is sample code
$courseCnt = array();
foreach($courseList as $course){
$courseCnt[$course['location']][$course['instructor']] += 1
}
This code creates the array properly and displays well but I get a bunch of warnings like:
Unidentified index "Orlando" for locations, Unidentified index "John
Smith" for instructor
I have found that if I just make it = 1 instead of += 1 the warnings go away but of course this makes every course for location/instructor 1 which is not good.
My next though was checking if it exists, if it doesn't, make it 1 and if it does += 1. Here is an example
if(isset($courseCnt[$course['location']][$course['instructor']]){
$courseCnt[$course['location']][$course['instructor']] += 1
}else{
$courseCnt[$course['location']][$course['instructor']] = 1
}
This results in the fatal error:
Cannot use string offset as an array
$course array structure is just a 2 dimensional array pulled from sql
Sample:
courseID location instructor
1 Orlando John Smith
2 Detroit Bill Murray
You are not checking if the location exists before checking for the instructor in your first line of the new version of the code. You need to check if it exists and create it in your $courseCnt array if it doesn't (as an empty array). After that, you can check for the instructor:
// Initialise the empty array
$courseCnt = array();
// Create location if not in array
if( ! isset($courseCnt[$course['location']])) {
$courseCnt[$course['location']] = array();
}
// Either increment the instructor or create with initial value of 1
if ( isset($courseCnt[$course['location']][$courseCnt[$course['instructor']]]) ) {
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}
You've got a lot of square brackets going on in there, so you might find it easier to read if you use PHP's array_key_exists (documentation) instead of isset:
// Initialise the empty array
$courseCnt = array();
// Create location if not in array
if( ! array_key_exists($course['location'], $courseCnt)) {
$courseCnt[$course['location']] = array();
}
// Either increment the instructor or create with initial value of 1
if ( array_key_exists($course['instructor'], $courseCnt[$course['location']]) ) {
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}
Related
I am getting duplicate data in an array and that data is storing in my DB. I am using array_unique to refine the duplicate data but it is not working. Please tell me is there any other way to make data unique and store in DB this way.
if (preg_match($keywords, $links[$i]->href)) {
if (filter_var($links[$i]->href, FILTER_VALIDATE_URL) !== false) {
array_push($mainNews, $links[$i]->href);
}
}
return (array_unique($mainNews));
Error I am getting:
Undefined array key 1 at C:\xampp\htdocs\pacra-crawlers\modules\crawlers\services\MainNewsRepository.php:46
for ($i = 0; $i < count($mainNewsLinks); $i++) {
$mainNews = new MainNews();
$mainNews->newspaper_id = $this->newspaperId;
$mainNews->sector_id = $sectorId;
$mainNews->url = $mainNewsLinks[$i];
$mainNews->save();
}
return ['status' => true];
}
C:\xampp\htdocs\pacra-crawlers\modules\crawlers\services\MainNewsRepository.php:46
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined array key 1", "C:\xampp\htdocs\pacra-crawlers\modules\crawlers\services\MainNewsRepo
sitory.php")
array_unique is working however although it is removing duplicates it is maintaining the same keys i.e.
If you had the following items in an array with
position/key value
0 a
1 a
2 b
array_unique would return
position/key value
0 a
2 b
which is why you are getting the Undefined array key when looping through the array based on the incrementing index $i.
Based on your sample you could use a foreach loop since you are only interested in the value eg
foreach($mainNewsLinks as $mainNewsLink) {
$mainNews = new MainNews();
$mainNews->newspaper_id = $this->newspaperId;
$mainNews->sector_id = $sectorId;
$mainNews->url = $mainNewsLink;
$mainNews->save();
}
If you would like to continue indexing or iterating through each element based on an index, you could use array_values in your return eg
return array_values(array_unique($mainNews));
from your function to reset the array keys to incrementing indexes
I'm trying to filter some logs like I need them and tried to it dynamic. I have some domains and I'm trying to filter some things from it, and it all works like I want it - but now I changed the domain name and now my code doesn't work anymore. It says one variable isn't defined.
$sp_bots = shell_exec("grep bot | awk '{print $12}' /var/www/laravel/logs/vhosts/domain.log");
$array_sp_bots = explode("\n", $sp_bots);
$all_bots = array();
foreach($array_sp_bots as $bots){
if(strpos($bots, "bot")){
$all_bots[] = $bots;
}
}
# count values of strings in array
if (!empty( $all_bots )) {
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}
and in my returns:
return view('/domains/data', [
'count_bots' => $count_bots,
'bot_keys' => $bot_keys,
'mostOccuring' => $mostOccuring,
]);
but all three variables in my return are undefined.. anybody knows why?
You have to initialize the array as an empty array before the loop:
$all_bots = array(); //init the empty array
foreach($array_sp_bots as $bots)
{
if(strpos($bots, "bot"))
{
$all_bots[] = $bots; //here you can add elements to the array
}
}
in your case, if the loop does not execute at least one time, the variable $all_bots will be undefined
EDIT
After the loop, to handle the case when the array is empty do somthing like this:
//if there is some element in all_bots...
if ( ! empty( $all_bots ) )
{
# count values of strings in array
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}
//handle the case the variable all_bots is empty
else
{
$bots = 0;
$count_bots = 0;
$bot_keys = 0;
$mostOccuring = 0;
}
EDIT2
You have the variables undefined in your return because when all $all_bots is empty they are not set. Check my edit above, i have added them to the if statement. But you have to handle this case in your application according to your needs, think this way: What these variables should contain when $all_bots is empty? Then assign the values to the variables in the if statement
It is happening because after changing the domain it is not executing inside the loop. Try with -
$all_bots= array(); // Define an empty array
foreach($array_sp_bots as $bots){
if(strpos($bots, "bot")){
$all_bots[] = $bots;
}
}
# count values of strings in array
$bots = array_count_values($all_bots);
If the $array_sp_bots is empty then it would not execute the loop & $all_bots would not be defined. For that case the count would be 0.
Or may might want to add some check for that -
if(empty($all_bots)) {
// Some error message
} else {
# count values of strings in array
$bots = array_count_values($all_bots);
arsort($bots);
$mostOccuring = max(array_count_values($all_bots));
$bot_keys = array_keys($bots);
#number of total bots
$count_bots = count($all_bots);
}
i need to make an array like this
$privateMsgIdArray = array("idlistener" => $idlistener, "maxMsgId" => $lastMsgId);
I need to replace the maxMsgId to the corresponding idlistener, and if the idlistener that i pass doesn't not exist to create a new entry inside the array.
I am a but confused on how i am going to extract the maxMsgId value corresponding to an idlistener.
In other words i need to pass new values of idlisteners only once, and replace maxMsgId each time that they are not equal to the corresponing idlistener.
If the idlistener field doesn't exist create it (push into array).
I pass old array into a session and new array in the current run.
After the run i i replace them.
I believe this sounds a bit confusing though.
e.g
We have an array like this already:
[15][200]
next call maxMsgId is 210
array should be
[15][210]
next call we have a new listener id with maxMsgId 30
array should be
[15][210]
[16][30]
You should be able to accomplish this with a quick loop:
// your "new" values
$idListener = 15;
$maxMsgId = 210;
// loop over the array to see if it contains the `idlistener` you want
$end = count($privateMsgIdArray);
for ($i = 0; $i < $end; $i++) {
if ($privateMsgIdArray[$i]['idlistener'] == $idListener) {
// we found it! overwrite the `maxMsgId` field
$privateMsgIdArray[$i]['maxMsgId'] = $maxMsgId;
break;
}
}
if ($i == $end) {
// we reached the end of the array without finding the `$idListener`;
// add a new entry =]
$privateMsgIdArray[] = array(
'idlistener' => $idListener,
'maxMsgId' => $maxMsgId
);
}
This is a rather brute-force approach though and, if efficiency is something you're after, it would be wise to create a "cache"-style method of idlistener values and their index in the $privateMsgIdArray array.
For instance:
// key = idlistener, value = index in `$privateMsgIdArray`
$idCache = array(15 => 0, 16 => 1);
// check if the `$idListener` is in the cache
if (!isset($idCache[$idListener])) {
// it's not; add a new entry
$key = count($privateMsgIdArray);
$privateMsgIdArray[$key] = array(
'idlistener' => $idListener,
'maxMsgId' => $maxMsgId
);
// add the new index into the cache
$idCache[$idListener] = $key;
} else {
// it is in the cache; pull the corresponding index and set the `maxMsgId` =]
$privateMsgIdArray[$idCache[$idListener]]['maxMsgId'] = $maxMsgId;
}
Both of the approaches above could be converted into functions to make things "more portable" too.
Hello I have a code that checks for duplicates inside an xml file:
XML:
<?xml version="1.0"?>
<profielen>
<profiel>
<voornaam>a</voornaam>
<achternaam>a</achternaam>
<adres>a</adres>
<postcode>a</postcode>
<plaats>a</plaats>
<email>a</email>
</profiel>
<profiel>
<voornaam>b</voornaam>
<achternaam>b</achternaam>
<adres>b</adres>
<postcode>b</postcode>
<plaats>b</plaats>
<email>b</email>
</profiel>
<profiel>
<voornaam>c</voornaam>
<achternaam>c</achternaam>
<adres>c</adres>
<postcode>c</postcode>
<plaats>c</plaats>
<email>c</email>
</profiel>
<profiel>
<voornaam>c</voornaam>
<achternaam>c</achternaam>
<adres>c</adres>
<postcode>cL</postcode>
<plaats>c</plaats>
<email>c</email>
</profiel>
</profielen>
I can select 6 checkboxes, the more are selected the more it filters. If I select firstname, only a,b and the first person with the name c can stay and the second one will be ignored.
Now I have this code:
$xml = simplexml_load_file('/xampp/htdocs/UploadifyZWP/uploads/profiel.xml');
//Load the xml file into an array
$myArray = $_REQUEST['checkboxarray'];
//Contains the selected value (firstname = 0,lastname = 1 etc..)
if(count($myArray) <1){
//If $myArray is empty it means no checkboxes are selected and there will be no filtering
count($xml);
}else{
$fields = $myArray;
//If at least one field is selected, this code runs:
switch(count($myArray)){
case 1:
//One checkbox selected
//Array where the profiles go withouth duplicates
$profile = array();
$passed = 0;
$teller = 0;
//Loops through all the profiles in the xml array
while($passed < count($xml)){
$add = false;
//Checks for all the selected values, 1 checkbox is selected so only 0 (firstname) is selected and goes into $field
foreach($fields as $field){
if(count($profile) < 1){
//If profile is empty, add the first profile from the xml array
$add = true;
}else {
if($profile[$teller][$field] != $xml->profiel[$teller][$field])
{
$add = true;
break;
}else{
$teller++;
$passed++;
}
}
}
if($add = true){
//toevoegen
$profile[$teller] = $xml->profiel[$teller];
$teller++;
$passed++;
}
}
echo count($profile);
print_r($profile);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
default: echo "error";
}
}
So I put all the correct profiles in $profile array and the duplicate will be ignored. Now for testing I print the array profiles to see if it did what it should do, but the outcome is not what I was looking for. The first one (a) will be added to $profiles, the second one (b) will not, the third one (c) is added again and the fourth (duplicate(d)) is not. Now if I add 2 more profiles (e,f), e will be added and f will not. Now I have troubles installing a debugger so I don't see where it is going wrong. I also get an error that says:
Notice: Undefined offset: 1 in C:\xampp\htdocs\UploadifyZWP\ontdubbelen.php on line 37
And
Notice: Undefined offset: 3 in C:\xampp\htdocs\UploadifyZWP\ontdubbelen.php on line 37
Does anyone see where it is going wrong and why?
On this line if($profile[$teller][$field] != $xml->profiel[$teller][$field]) you have specified a third level of a multidimensional array but your data has only 2 levels as shown below.
SimpleXMLElement Object
(
[voornaam] => a
[achternaam] => a
[adres] => a
[postcode] => a
[plaats] => a
[email] => a
)
Try this instead
if($profile[$teller] != $xml->profiel[$teller])
There are a few issues with this code, but the main one is that some of the logic in it is flawed.
I'll start by saying that the if statement if($add = true) will always return true, since you are assigning rather than comparing. You need to use if ($add == true) to perform a comparison.
Other than that, it's quite hard to say exactly what you're doing wrong, because it is a general failure in logic. The main issue comes down to the fact that, on the second iteration of your while loop (starting while($passed < count($xml))), the $profile array contains one element at index 0, (meaning that count($profile) < 1 returns false, but the value of $teller is now 1, since you incremented it in the first iteration. You then try to compare the value of $profile[$teller][$field], which fails, because there is no offset of 1 in your $profile array.
Edit
To check for the existence of an index in an array, you can use isset, for example
if (isset($profile[$teller]))
I am selecting checkboxes and want to save in an associative array with current page number $_GET['page_no'] as it's index, but only 1 value goes in, why no other?
$pageno = $_GET['page_no']; //Say page no is 1
$_SESSION['selected_vals'] = array();
foreach($_POST['record_num'] as $throw_rec_nums) {
$_SESSION['selected_vals'][$pageno] = $throw_rec_nums;
}
What I expect
$_SESSOION['selected_val'] (
[1] => 24
[1] => 46
[1] => 56
)
But I only get 24 even if 3 checkboxes are selected
Note: $_GET['page_no'] is returned as array
$pageno is not incrementing. In order for more than one value to be added to the array, it needs to be incremented while in the loop.
A solution would be something like:
$_SESSION['selected_vals'][$pageno][] = $throw_rec_nums;
That way all record numbers would be saved to the array at the page number specified.
Only 1 value goes in because your are replacing $_SESSION['selected_vals'][$pageno] value on each loop of foreach.
try create a counter to index it
it is a option
$_SESSION['selected_vals'] = array();
$_SESSION['selected_vals'][$pageno] = array();
foreach($_POST['record_num'] as $throw_rec_nums) {
$_SESSION['selected_vals'][$pageno][] = $throw_rec_nums;
}
You cannot use an array as array index. You will have to iterate over $pageno too, for example with next():
$array[current($pageno)] = ...;
next($pageno);
Note that this will only work if you make sure rt that $pageno actually IS an array and contains enough elements.