How to check duplicate value inside foreach loop - php

I have 3 array like this from foreach loop
$link = 'https://example.com/page/';
$parse = explode('/', $link);
for ($i = 0;$i <= 5;$i++)
{
if($i > 0) {
$link = $parse[0]."//".$parse[1]."/".$parse[2]."/".$parse[3]."/".$parse[4].$i;
$get[$i] = curl($link);
$re = '/class="img-lazy" src="(.*?)"/m';
preg_match_all($re, $get[$i], $matches);
foreach ($matches[1] as $content)
{
echo $content. "\r\n";
}
}
}
(loop from each page eg: example.com/page/1 will contain the array below and so on with page 2/3...)
Result:
Array (Page 1)
(
[0] => https://example.com/img1.jpg
[1] => https://example.com/img2.jpg
)
Array (Page 2)
(
[0] => https://example.com/img3.jpg
[1] => https://example.com/img4.jpg
)
Array (Page 3 nonexist auto redirect to page 1)
(
[0] => https://example.com/img1.jpg
[1] => https://example.com/img2.jpg
)
The last one is duplicate. How do i remove it ?
I already tried to merge the array and array_unique function. But the duplicate one still there.

Quick solution run for loop only 5 times if loop is dynamic follow this answer
What I did is compare very first link. if it repeat then exit.
I checked and it works fine
your images are nice :-)
$get = array();
$firstcompare = 0;
$firsttime = 1;
for ($i = 0;$i <= 17;$i++)
{
if($i > 0) {
$dup = $res = [];
$link = $parse[0]."//".$parse[1]."/".$parse[2]."/".$parse[3]."/".$parse[4].$i;
$get[$i] = curl($link);
$re = '/class="aligncenter" src="(.*?)"/m';
preg_match_all($re, $get[$i], $matches);
if($firsttime){
$stringlink = $matches[1][0];
$firsttime = 0;
}
foreach ($matches[1] as $content)
{
if($firstcompare){
if ($stringlink==$content) {
exit;
}else{
// echo $content."\n\n";
echo "<img src=' $content ' /> " . "\r\n";
}
}else{
// echo $content."\n\n";
$firstcompare = 1;
echo "<img src=' $content ' /> " . "\r\n";
}
}
}
}

You may try like this as per yourArray, hope it will help you
Using Foreach:
$dup = $res = [];
foreach($yourArray as $arr){
$imploded = #implode(',',$arr);
if(!in_array($imploded, $dup)){
$dup[] = $imploded;
$res[] = $arr;
}
}
(or)
Using Array Function:
$unique = array_unique(array_map(function($arr){
return #implode(',',$arr);
}, $yourArray));
$mapped = array_map(function($a){
return #explode(',', $a);
}, $unique_data);

I don't really understand everything but to remove duplicate data inside an array you can use the array_unique() function.
foreach(array_unique($yourArray) as $value):
// Code goes here
endforeach;
It takes the array and return the clean one
https://www.php.net/manual/fr/function.array-unique.php

Here is the best way to remove duplicate values from the multi-dimensional array by using PHP or Laravel.
Solution:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
$input = Array
(
[0] => Array
(
[0] => abc
[1] => def
)
[1] => Array
(
[0] => ghi
[1] => jkl
)
[2] => Array
(
[0] => mno
[1] => pql
)
[3] => Array
(
[0] => abc
[1] => def
)
[4] => Array
(
[0] => ghi
[1] => jkl
)
[5] => Array
(
[0] => mno
[1] => pql
)
)
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Output :
Array
(
[0] => Array
(
[0] => abc
[1] => def
)
[1] => Array
(
[0] => ghi
[1] => jkl
)
[2] => Array
(
[0] => mno
[1] => pql
)
[3] => Array
(
[0] => ghi
[1] => jkl
)
[4] => Array
(
[0] => mno
[1] => pql
)
)

Related

Is there any oneliner for a kind of explode and concat in PHP

I got string like 1_2_3_4_5 and I want an array like this:
array(
[0] = 1
[1] = 1_2
[2] = 1_2_3
[3] = 1_2_3_4
[4] = 1_2_3_4_5
)
Any idea for a oneliner?
just for fun using substr
$st = '1_2_3_4_5';
$num[]=$st;
while($pos=strrpos($st,'_')){
$num[]=$st=substr($st,0,$pos);
}sort($num);
print_r($num);
Output
(
[0] => 1
[1] => 1_2
[2] => 1_2_3
[3] => 1_2_3_4
[4] => 1_2_3_4_5
)
<?php
$input = '1_2_3_4_5';
// Get an array with 1, 2, 3, 4 and 5
$parts = explode('_', $input);
$output = [];
$i = 1;
foreach ($parts as $part) {
// array_slice() will take 1 to n elements from the array of numbers
$values = array_slice($parts, 0, $i++);
// Join the values
$output[] = implode('_', $values);
}
print_r($output);
It will show this:
Array
(
[0] => 1
[1] => 1_2
[2] => 1_2_3
[3] => 1_2_3_4
[4] => 1_2_3_4_5
)
Try it at 3V4L.

convert a string to multi dimensional array in php

I'm having trouble converting a string to a multi-dimensional array in php. This is my string:
$String = a,b,c|d,e,f|g,h,y|
This is what I'm trying:
$one=explode("|",$String);
foreach ($one as $item)
{
$one=explode(",",$one);
}
I'd like to create this array:
$array={ {a,b,c}, {d,e,f}, {g,h,y} };
Try with -
$one=explode("|",$String);
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
Try this code:
$string = 'a,b,c|d,e,f|g,h,y|';
$arr = array_map(function($iter){ return explode(',',$iter);},explode('|',$string));
Hope it help a bit.
You have almost done it right, except for the cycle part. Try this
$result = [];
$String = 'a,b,c|d,e,f|g,h,y|';
$firstDimension = explode('|', $String); // Divide by | symbol
foreach($firstDimension as $temp) {
// Take each result of division and explode it by , symbol and save to result
$result[] = explode(',', $temp);
}
print_r($result);
Try this-
$String = 'a,b,c|d,e,f|g,h,y|';
$one = array_filter(explode("|", $String));
print_r($one); //Array ( [0] => a,b,c [1] => d,e,f [2] => g,h,y )
$result = array_map('v', $one);
function v($one) {
return explode(',',$one);
}
print_r($result); // Array ( [0] => Array ( [0] => a [1] => b [2] => c ) [1] => Array ( [0] => d [1] => e [2] => f ) [2] => Array ( [0] => g [1] => h [2] => y ) )
Use this code
$String= 'a,b,c|d,e,f|g,h,y|';
$one=explode("|",$String);
print_r(array_filter($one));
Output will be
Array
(
[0] => a,b,c
[1] => d,e,f
[2] => g,h,y
)

PHP: Parsing data within multidimensional array

I have an array which looks like this:
Array
(
[0] => Array
(
[0] => TE=140414100000 cd =AB1234 ggg =1234567 gbh =2
[7] => nd: DA1AAAAAAAAAA: TD = 140414:
)
[1] => Array
(
[0] => TE=140414100000 cd =AB1234 ggg =1234567 ghb =2
[7] => nd: DA1AAAAAAAAAA: TD = 140414:
)
)
what I am trying to acomplish is to parse data within each sub array and create a new multidimensional array with the parsed data.
Example: the data in parentheses below is what should be returned in new multidimensional array
Array
(
[0] => Array
(
[0] => te=(140414100000) cd =AB(1234) ggg =1234567 ghb =2
[7] => nd: DA(1)(AAAAAAAAAA): TD = (140414):
)
[1] => Array
(
[0] => te=(140414100000) cd =AB(1234) ggg =1234567 ghb =2
[7] => nd: DA(2)(BBBBBBBBBB): TD = (140414):
)
)
What I want to return:
Array
(
[0] => Array
(
[0] => 140414100000
[1] => 1234
[2] => 1
[3] => AAAAAAAAAA
[4] => 140414
)
[1] => Array
(
[0] => 140414100000
[1] => 1234
[2] => 2
[3] => BBBBBBBBBB
[4] => 140414
)
).
So my question is what would be the best way to acomplish this?
This is what I have come up with. It works, however is seems very inefficient as it adds a lot of empty arrays which have to be cleaned up.
foreach($new as $key => $val){
foreach($val as $res){
preg_match_all('%te=([0-9]{12})\s%',$res,$matches);
$out[$key][] = $matches[1][0];
preg_match_all('%cd\s+=AB([0-9]{4})%',$res,$matches);
$out[$key][] = $matches[1][0];
preg_match_all('%nd:\sDA([0-9]{1})%',$res,$matches);
$out[$key]['node'] = $matches[1][0];
preg_match_all('%nd:\sDA[0-9]{1}([a-zA-Z]{10,14}):%',$res,$matches);
$out[$key]['rset'] = $matches[1][0];
preg_match_all('%td\s=\s([0-9]{6}):%',$res,$matches);
$out[$key]['trdt'] = $matches[1][0];
}
}
foreach($out as $v){
$v = array_values(array_filter($v));
$return[] = $v;
}
return $return;
Thanks in advance.
UPDATED:
This worked and is much more efficient. Thanks for the example Shankar
foreach($new as $key => $val){
$v = implode('', $val);
preg_match_all("%te=([0-9]{12})|cd\s+=AB([0-9]{4})|nd:\sDA([0-9]{1})|([A-Z]{3,7}):|td=\s([0-9]{6}):%",$v,$matches);
$new_array[$key]['time'] = $matches[1][0];
$new_array[$key]['code'] = $matches[2][1];
$new_array[$key]['sp'] = $matches[3][2];
$new_array[$key]['rset'] = $matches[4][3];
$new_array[$key]['trfdt'] = $matches[5][4];
}
echo "<pre>";
print_r($new_array);
echo "</pre>";
Loop through your array and implode each array element and use a preg_match_all() to capture all the entries bewteen ( and ) and then pass those matches to your new array.
foreach($arr as $k=>$arr1)
{
$v = implode('',$arr1);
preg_match_all('^\((.*?)\)^', $v, $matches);
$new_arr[]=$matches[1];
}
print_r($new_arr);
Working Demo

Building a recursive function to create a multidimensional array

I think what I want is a recursive function, but please let me know if there's another way to achieve what I want to do! I'm not sure I'm going to explain this very well, so please let me know if you need further clarification.
I've got a function, findSeed() which takes an id and returns an array that contains information about the "seed":
function findSeeds($id) {
global $wpdb;
$query = "SELECT * FROM seedTable WHERE id = " . $id;
$seed = $wpdb->get_row($query, ARRAY_A);
return $seed;
}
It returns the following array:
Array
(
[id] => 9
[name] => Sign
[seed1] => 4
[seed2] => 3
)
Where seed 1 and seed 2 are the ids of the seeds needed to create it. I'm looking to make a function that will create a multidimensional array, in the following format, where the first part of the array contains the first "seed", the next contains the two seeds contained in the first, the next contains the two seeds contained in each of those, and so on:
Array
(
[1] => Array
(
[0] => Stripey Wallpaper
)
[2] => Array
(
[0] => Green Block
[1] => Aqua Block
)
[3] => Array
(
[0] => Bricks
[1] => Grass
[2] => Bricks
[3] => Glass Pane
)
[4] => Array
(
[0] => Rock
[1] => Grass
[2] => Dirt
[3] => Rock
[4] => Rock
[5] => Grass
[6] => Rock
[7] => Lava
)
)
I'm doing it so far with a (horrible) function, shown here, but the "map" could be anything between 2 and 8 rows, and I'm struggling to see how to turn it into a neat little function that works for anything:
function makeMap($id) {
// First Row
$rowNum = 1;
$oneSeed = findSeeds($id);
$map[$rowNum][] = $oneSeed[name];
// Second Row
$rowNum = $rowNum + 1;
$twoSeed = findSeeds($oneSeed[seed1]);
$threeSeed = findSeeds($oneSeed[seed2]);
$map[$rowNum][] = $twoSeed[name];
$map[$rowNum][] = $threeSeed[name];
// Third Row
$rowNum = $rowNum + 1;
$fourSeed = findSeeds($twoSeed[seed1]);
$fiveSeed = findSeeds($twoSeed[seed2]);
$sixSeed = findSeeds($threeSeed[seed1]);
$sevenSeed = findSeeds($threeSeed[seed2]);
$map[$rowNum][] = $fourSeed[name];
$map[$rowNum][] = $fiveSeed[name];
$map[$rowNum][] = $sixSeed[name];
$map[$rowNum][] = $sevenSeed[name];
// Fourth Row
$rowNum = $rowNum + 1;
$eightSeed = findSeeds($fourSeed[seed1]);
$nineSeed = findSeeds($fourSeed[seed2]);
$tenSeed = findSeeds($fiveSeed[seed1]);
$elevenSeed = findSeeds($fiveSeed[seed2]);
$twelveSeed = findSeeds($sixSeed[seed1]);
$thirteenSeed = findSeeds($sixSeed[seed2]);
$fourteenSeed = findSeeds($sevenSeed[seed1]);
$fifteenSeed = findSeeds($sevenSeed[seed2]);
$map[$rowNum][] = $eightSeed[name];
$map[$rowNum][] = $nineSeed[name];
$map[$rowNum][] = $tenSeed[name];
$map[$rowNum][] = $elevenSeed[name];
$map[$rowNum][] = $twelveSeed[name];
$map[$rowNum][] = $thirteenSeed[name];
$map[$rowNum][] = $fourteenSeed[name];
$map[$rowNum][] = $fifteenSeed[name];
return $map;
}
It should stop when all the "row" nodes are blank, so the following only needs to return the first two "rows":
Array
(
[1] => Array
(
[0] => Wood Block
)
[2] => Array
(
[0] => Dirt
[1] => Lava
)
[3] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
[4] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
)
)
Any tips, hints or solutions would be GREATLY appreciated,
Thank you.
Edit: Quick note on why I'd like it in the above format - I'm then printing out the results in a table, with the first seed spanning the entire row, then breaking it down with the children underneath, like so:
$map = makeMap($_POST['theItem']);
$colspan = count(end(array_values($map)));
echo '<h3>' . $map[row1][0] . '</h3><br/>';
echo '<table>';
foreach ($map as $row) {
echo '<tr>';
foreach ( $row as $cell) {
echo '<td colspan="'. $colspan .'"><div class="seed">' . $cell . '</div></td>';
}
$colspan = $colspan / 2;
echo '</tr>';
}
echo '</table>';
<?php
$array = array('one', 'two', 'three');
for($i =1; $i<= count($array); $i++){
for($j=0; $j<$i; $j++){
$arrymulti[$i][$j]= $array[$j];
}
}
echo '<pre>';
print_r($arrymulti);
?>
Output:
Array
(
[1] => Array
(
[0] => one
)
[2] => Array
(
[0] => one
[1] => two
)
[3] => Array
(
[0] => one
[1] => two
[2] => three
)
)
DEMO
You can Use this recursive function That I Wrote It For Class
static public $map;
static function seeder($id,$Depth=0){
$Seed=findSeeds($id);
if(!$Seed){
return self::$map;
}
self::$map[$Depth][]=$Seed['name'];
self::seeder($Seed['seed1'],$Depth+1);
self::seeder($Seed['seed2'],$Depth+1);
if($Depth==0){
foreach(self::$map as $k=>$v){
$Flag=true;
foreach($v as $key=>$Value){
if($Value!="")$Flag=false;
}
if($Flag){
for($i=$k;$i<=count(self::$map);$i++){
#unset(self::$map[$i]);
}
break;
}
}
}
return self::$map;
}
Sample
print_r(seeder($ID));
The output Is similar of Your sample

PHP Group array by values

I have an array like this:
Array (
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
[4] => ing_2_ing
[5] => ing_2_amount
[6] => ing_2_det
[7] => ing_2_meas
)
And I want to group the values into an array like this:
Array (
[0] => Array(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[1] => Array(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
There may be many other items named like that: ing_NUMBER_type
How do I group the first array to the way I want it? I tried this, but for some reason, strpos() sometimes fails:
$i = 1;
foreach ($firstArray as $t) {
if (strpos($t, (string)$i)) {
$secondArray[--$i][] = $t;
} else {
$i++;
}
}
What is wrong? Can you advice?
It depends what you are trying to achieve, if you want to split array by chunks use array_chunk method and if you are trying to create multidimensional array based on number you can use sscanf method in your loop to parse values:
$result = array();
foreach ($firstArray as $value)
{
$n = sscanf($value, 'ing_%d_%s', $id, $string);
if ($n > 1)
{
$result[$id][] = $value;
}
}
<?php
$ary1 = array("ing_1_ing","ing_1_amount","ing_1_det","ing_1_meas","ing_2_ing","ing_2_amount","ing_2_det","ing_2_meas");
foreach($ary1 as $val)
{
$parts = explode("_",$val);
$ary2[$parts[1]][]=$val;
}
?>
This creates:
Array
(
[1] => Array
(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[2] => Array
(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
What I'd do is something like this:
$result = array();
foreach ($firstArray as $value)
{
preg_match('/^ing_(\d+)_/', $value, $matches);
$number = $matches[1];
if (!array_key_exists($number, $result))
$result[$number] = array();
$result[$number][] = $value;
}
Basically you iterate through your first array, see what number is there, and put it in the right location in your final array.
EDIT. If you know you'll always have the numbers start from 1, you can replace $number = $matches[1]; for $number = $matches[1] - 1;, this way you'll get exactly the same result you posted as your example.

Categories