what should I use instead of array_unique in php? - php

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

Related

Foreach loop over array of objects Laravel

I'm receiving this array of objects and need to iterate over it, but the problem is that I need to get the value of the next item when its iterating, to compare the value of the current object with the next one, and if it's a different value, split this array in two.
So, I was doing it with next() php function:
//looking for the next register in the array
$next = next($finances);
//first array if exist different values
$aiuaEd = [];
//second array if exist different values
$aiua = [];
foreach ($finances as $finance) {
if ($finance->cnpj <> $next->cnpj) {
$aiua[] = $finance;
} else {
$aiuaEd[] = $finance;
}
}
This code works fine at some point, but then I got this error:
Trying to get property 'cnpj' of non-object in
I don't know why sometimes works well and sometimes don't, debugging this variables, I found that if my array have 2 objects inside only, when I'm looping over it, the $next->cnpj variable came as empty, and sometimes don't.
Can someone help me with this?
I solved it with a different approach, instead of using php next(), I first loop over this array saving the cnpj's into an array.
$cnpjs = [];
foreach($finances as $finance){
$cnpj[] = $finance->cnpj;
}
Then I use array_unique() to group this 2 differents CNPJ's and sort() to get the correct keys order.
//grouping cnpjs as unique, should exist only 2 keys
$cnpj = array_unique($cnpj);
//sort array keys to get in order
sort($cnpj);
Then I iterate over my $finances array again, but now I'm counting if this $cnpj array has more than 2 positions, which means that I have to split this data in two differents arrays.
foreach($finances as $finance){
if(count($cnpj) > 1){
if($finance->cnpj == $cnpj[1]){
$aiua[] = $finance;
}else{
$aiuaEd[] = $finance;
}
}else{
$aiuaEd[] = $finance;
}
}
I'm pretty sure that this is not the best approach for that problem, or at least the most optimized one, so I'm open for new approach's suggestions!
Just posting how I solved my problem in case anyone having the same one.
Notice that this approach is only usable because I know that will not exist more than 2 different's CNPJ's in the array.

Looking for an element in an array in PHP

I don't know if I'm managing this array in the best way.
The array I have is this:
$bass = $_POST['bass'];
$selected_scale = $_POST['scale'];
$major_scales = array
(
array("C","D","E","F","G","A","B","C","D","E","F","G","A","B",),
array("C#","D#","E#","F#","G#","A#","B#","C#","D#","E#","F#","G#","A#","B#",),
array("Db","Eb","F","Gb","Ab","Bb","C","Db","Eb","F","Gb","Ab","Bb","C",),
array("D","E","F#","G","A","B","C#","D","E","F#","G","A","B","C#"),
array("D#","E#","F##","G#","A#","B#","C##","D#","E#","F##","G#","A#","B#","C##"),
array("Eb","F","G","Ab","Bb","C","D","Eb","F","G","Ab","Bb","C","D"),
array("E","F#","G#","A","B","C#","D#","E","F#","G#","A","B","C#","D#"),
array("E#","F##","G##","A#","B#","C##","D##","E#","F##","G##","A#","B#","C##","D##"),
array("Fb","Gb","Ab","Bbb","Cb","Db","Eb","Fb","Gb","Ab","Bbb","Cb","Db","Eb"),
array("F","G","A","Bb","C","D","E","F","G","A","Bb","C","D","E"),
array("F#","G#","A#","B","C#","D#","E#","F#","G#","A#","B","C#","D#","E#"),
array("Gb","Ab","Bb","Cb","Db","Eb","F","Gb","Ab","Bb","Cb","Db","Eb","F"),
array("G","A","B","C","D","E","F#","G","A","B","C","D","E","F#"),
array("G#","A#","B#","C#","D#","E#","F##","G#","A#","B#","C#","D#","E#","F##"),
array("Ab","Bb","C","Db","Eb","F","G","Ab","Bb","C","Db","Eb","F","G"),
array("A","B","C#","D","E","F#","G#","A","B","C#","D","E","F#","G#"),
array("A#","B#","C##","D#","E#","F##","G##","A#","B#","C##","D#","E#","F##","G##"),
array("Bb","C","D","Eb","F","G","A","Bb","C","D","Eb","F","G","A"),
array("B","C#","D#","E","F#","G#","A#","B","C#","D#","E","F#","G#","A#"),
array("B#","C##","D##","E#","F##","G##","A##","B#","C##","D##","E#","F##","G##","A##"),
array("Cb","Db","Eb","Fb","Gb","Ab","Bb","Cb","Db","Eb","Fb","Gb","Ab","Bb")
);
$bass is a string, like the one inside the arrays. The $selected_scale is just a number.
What I'm trying to do is to find the $bass in one of those array in the position of $selected_scale. Basically, $bass = $major_scales[$selected_scale]. Therefore I want to create a loop in order to get the elements after that.
But I don't know how to manage in this case the situation. I've looked everything in internet and try various solutions without success. I'd like to know how can I do it. Thanks
Try to use next loop:
// if value exists in mentioned index
if (in_array($bass,$major_scales[$selected_scale])){
// index of that value in that array
$tmp_ind = array_search($bass,$major_scales[$selected_scale]);
// length of the array
$len = count($major_scales[$selected_scale]);
// store values after this value
$res = [];
for ($i=$tmp_ind;$i<$len;$i++){
$res[$i] = $major_scales[$selected_scale][$i];
}
}
print_r($res);
Demo1
If you need to find value by index $selected_scale in one of these arrays and also store values after this position:
foreach($major_scales as $ar){
if ($ar[$selected_scale] == $bass){
// length of the array
$len = count($ar);
// store values after this value
$res = [];
for ($i=$selected_scale;$i<$len;$i++){
$res[$i] = $ar[$i];
}
}
}
print_r($res);
Demo2

PHP getting random from array return null sometimes

in one array in php i have only one index and data into that, for example:
array:1 [
0 => "{"pk":"4760991153","username":".....","full_name":".....","is_private":true}"
]
in this array i don't know how many data stored into that and when i try to get random index from to access to this index of array i get null sometimes, for example:
$userPages[]=[
'{"pk":"4760991153","username":".....","full_name":".....","is_private":true}'
];
$data = $userPages[rand(0, count($userPages) - 1)
echo json_decode($data)->pk;
or
$randomSelectedTag = array_rand($userPages);
$data = $userPages[$randomSelectedTag];
echo json_decode($data)->pk;
output:
"4760991153",
"4760991153",
"4760991153",
null
"4760991153",
null
how can i fix this problem to make sure getting random from the array don't return null?
If your items have missing keys, don't use rand(0, count($userPages) - 1) as it counts how many items are in the array and returns a random 0-n, not the actual key.
So use array_rand($userPages)
<?php
$userPages=[
0 => '{"pk":"1","username":".....","full_name":".....","is_private":true}',
8 => '{"pk":"2","username":".....","full_name":".....","is_private":true}',
12 => '{"pk":"3","username":".....","full_name":".....","is_private":true}',
64 => '{"pk":"4","username":".....","full_name":".....","is_private":true}'
];
for ($i=0; $i < 10; $i++) {
$data = $userPages[array_rand($userPages)];
echo json_decode($data)->pk.PHP_EOL;
}
https://3v4l.org/JcQea
Or reset the keys, with array_values() then your other method would work.
https://3v4l.org/2HWcG
There is not an issue in the random index, since every random index is from existing array range $data = $userPages[rand(0, count($userPages) - 1).
Reason that causes null results is because you don't check if pk property exists in object, or is it not null. So you should do just simple check:
$randomSelectedTag = array_rand($userPages);
$data = $userPages[$randomSelectedTag];
if(isset($data->pk) && !is_null($data->pk)){
echo json_decode($data)->pk;
}

Assign values to an associated array in a loop

I am having a difficult time creating an associated array and assigning a value to the key. I have two arrays (tech_pay and tech_scans) and I am doing a simple calculation using their values and I want to create a new array called tech_per_scan but I keep getting an array with the key automatically created starting at 0.
$tech_per_scan = array();
foreach($tech_pay as $key=>$value)
{
$pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan
$tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan);
}
This line $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); will add an element to you array and it will start with 0 as its index, because you did not specify its key. Similar to array_push
It should be $tech_per_scan[$id]
$tech_per_scan[$id] = $pay_per_scan;
you should set value for new array like this :
$tech_per_scan[$key] = $pay_per_scan ;
Full code is :
$tech_per_scan = array();
foreach($tech_pay as $key=>$value)
{
$pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan
$tech_per_scan[$key] = $pay_per_scan ;
}

Function is changing array from numeric to associative

This is supposed to take any rows where ing_name is duplicated, combine the eff_name fields and delete the duplicate but it also has the side effect of changing the array from numeric to associative. My ajax is expecting numeric array.
for($i=count($recipe)-1; $i>0; $i--) {
if($recipe[$i]['ing_name'] == $recipe[$i-1]['ing_name']) { //check for duplicate. **array must be sorted by ing_name**
$recipe[$i-1]['eff_name'] .= ', '.$recipe[$i]['eff_name']; //Combine eff_name of duplicates
$recipe[$i-1]['link'] = true;
unset($recipe[$i]); //remove duplicate index
}
}
examples: NUM, ASSOC
Source
EDIT: So i figured it must have something to do with unsetting the index so I did this and it seems to work ok:
$newRecipe = array();
foreach($recipe as $r) {
$newRecipe[] = $r;
}
New question, is there a better way?
unset works with named keys. You could use array_splice instead, or get a brand new array after the loop with array_values (but that would be ugly!).
array_values() Will return a numerically indexed array

Categories