How to make array intersect in php? [duplicate] - php

This question already has answers here:
How to remove duplicate values from an array in PHP
(27 answers)
Closed last year.
This is my two arrays:
$head_office = array(600,400,534,678,601,90);
$Sb_office = array(600,400,530,678,600,90,84);
My desire output:
array(600,400,678,90);
I am trying:
print_r(array_intersect($Sb_office,$head_office));
Output:
Array ( [0] => 600 [1] => 400 [3] => 678 [4] => 600 [5] => 90 )
How can I avoid the value 600 ?
NB: I am not removing duplicate values. I want to get matched values between 2 arrays.

Use array_unique().
$head_office = array(600,400,534,678,601,90);
$Sb_office = array(600,400,530,678,600,90,84);
print_r(array_unique(array_intersect($Sb_office,$head_office)));
Output
Array ( [0] => 600 [1] => 400 [3] => 678 [5] => 90 )

It seams that you want to avoid duplicate value 600. you can do it using array_unique() like below
print_r(arry_unique(array_intersect($Sb_office,$head_office)));

Use array_unique
Additionally you can use array_values to alter the keys of new array.
$head_office = array(600,400,534,678,601,90);
$Sb_office = array(600,400,530,678,600,90,84);
print_r(array_values(array_unique(array_intersect($Sb_office,$head_office))));
OUTPUT
Array ( [0] => 600 [1] => 400 [2] => 678 [3] => 90 )

Swap $head_office and $Sb_office
<?php
$head_office = array(600,400,534,678,601,90);
$Sb_office = array(600,400,530,678,600,90,84);
print_r( array_intersect($head_office, $Sb_office) );
Output:
Array
(
[0] => 600
[1] => 400
[3] => 678
[5] => 90
)

I have gotten a partial answer:
print_r( array_intersect_assoc($head_office, $Sb_office) );

Related

Assign key number to php array objects

My code
$str = array(fgets($da, 1024));
print_r($str);
I'm trying to create an array in php from a dynamic output , but i noticed the keys in all object are [0], i need to assign a diferent key number to each object, how can i do that ?
Looks weird to me that all keys are 0, im trying to figure but nothing helps me.
Result :
Array
(
[0] =>
)
Array
(
[0] => 200
)
Array
(
[0] => 819105 rs fs
)
Array
(
[0] => 300 tert
)
Array
(
[0] => THO
)
Array
(
[0] => 91362
)
Array
(
[0] =>
)
Array
(
[0] => 06-20-21 6:56 PM
)
Array
(
[0] =>
)
Array
(
[0] =>
Array
(
[0] => 3 Cat 20 4.82 0.0 7.4 30
)
Array
(
[0] => 4 Dogs 19 26.2 0.8 7.1 62
)
Array
(
[0] =>
)
Thanks
If the input is reliable, you can split on whitespace for example:
$str = fgets($da, 1024);
$a = explode(" ", $str);
print_r($a);
array_merge with the spread (...) operator would work.
$str = array(fgets($da, 1024));
$str = array_merge(...$str);
All of the keys appear to be zero because you are wrapping each line from the file in its own array, so each array has one element at index zero.
If you define a buffer outside of your read loop, and add each line to it, each line will have its own index.
$da = fopen('test.txt', 'r');
// Define a buffer for the output
$data = [];
while (($str = fgets($da)) !== false)
{
// Add our line to the buffer
$data[] = $str;
}
fclose($da);
print_r($data);
output:
Array
(
[0] => 200
[1] => 819105 rs fs
[2] => 300 tert
[3] => THO
[4] => 91362
[5] => 06-20-21 6:56 PM
[6] => 3 Cat 20 4.82 0.0 7.4 30
[7] => 4 Dogs 19 26.2 0.8 7.1 62
)
But it looks like you may have some sort of header information in the first 6 lines of the file, maybe info from an HTTP request? Then lines that are somehow delimited, maybe by tab, but then the text got munged somewhere on the way into the SO post?
You can use a combination of fgets and fgetcsv to pull the data from the file and organize it into associative arrays.
Input:
200
819105 rs fs
300 tert
THO
91362
06-20-21 6:56 PM
3 Cat 20 4.82 0.0 7.4 30
4 Dogs 19 26.2 0.8 7.1 62
5 Wombat 20 4.20 0.0 6.9 30
6 Hedgehogs 19 26.2 0.8 7.1 62
$da = fopen('test.txt', 'r');
// Define a buffer for the output
$data = [];
// Define the fields in the header, each header line needs an entry
$headerDef = [
'status',
'transfer_stats',
'what_is_this',
'something_else',
'content_length',
'timestamp'
];
// Define the columns in the data rows, each column needs an entry
$columnDef = [
'id',
'type',
'count',
'average_weight',
'tax',
'food_weight_percent_per_day',
'fluffiness'
];
// Define an array to hold the header contents
$headerData = [];
// For each line in the header definition, extract a line from the file
while (!empty($headerDef) && $str = fgets($da, 1024))
{
$currValue = trim($str);
// Pull the next field from the front of the array
$currHeaderField = array_shift($headerDef);
// Set the entry in the header data array
$headerData[$currHeaderField] = $currValue;
}
while ($row = fgetcsv($da, 1024, "\t"))
{
// Create a new associative array by combining the column names and the row data
$data[] = array_combine($columnDef, $row);
}
fclose($da);
print_r($headerData);
print_r($data);
output:
Array
(
[status] => 200
[transfer_stats] => 819105 rs fs
[what_is_this] => 300 tert
[something_else] => THO
[content_length] => 91362
[timestamp] => 06-20-21 6:56 PM
)
Array
(
[0] => Array
(
[id] => 3
[type] => Cat
[count] => 20
[average_weight] => 4.82
[tax] => 0.0
[food_weight_percent_per_day] => 7.4
[fluffiness] => 30
)
[1] => Array
(
[id] => 4
[type] => Dogs
[count] => 19
[average_weight] => 26.2
[tax] => 0.8
[food_weight_percent_per_day] => 7.1
[fluffiness] => 62
)
[2] => Array
(
[id] => 5
[type] => Wombat
[count] => 20
[average_weight] => 4.20
[tax] => 0.0
[food_weight_percent_per_day] => 6.9
[fluffiness] => 30
)
[3] => Array
(
[id] => 6
[type] => Hedgehogs
[count] => 19
[average_weight] => 26.2
[tax] => 0.8
[food_weight_percent_per_day] => 7.1
[fluffiness] => 62
)
)
Of course the field names are just made up, I have no idea what your actual data is. And I'm assuming that the data rows are delimited with tabs, that may not be the case. But you should be able to use this as a starting point.
PS. It could be that the HTTP data at the top of the file is included by mistake, perhaps from a curl request? You could change that with the CURLOPT_HEADER option and curl_setopt

Looking for duplicated values in an array for a certain key [duplicate]

This question already has answers here:
Get the keys for duplicate values in an array
(11 answers)
Closed 4 years ago.
I have an array:
Array
(
[0] => Array
(
[sku_code_part_id] => 1
[part_label] => blue
[part_value] => BLU
)
[1] => Array
(
[sku_code_part_id] => 2
[part_label] => Orange
[part_value] => ORG
)
[2] => Array
(
[sku_code_part_id] => 3
[part_label] => Orange
[part_value] => ORG
)
[3] => Array
(
[sku_code_part_id] => 4
[part_label] => Orange
[part_value] => ORG
)
[4] => Array
(
[sku_code_part_id] => 5
[part_label] => Green
[part_value] => GRE
)
[5] => Array
(
[sku_code_part_id] => 6
[part_label] => Red
[part_value] => RED
)
)
I'm wanting a simple way of checking the array $this->request->post['custom_parts'] for the any duplicated values assigned to the part_value keys.
So I can flag an error that 'ORG' is duplicated numerous times.
I've tried various methods such as removing duplications and comparing before and after. However I'm running into a number of issues with this.
Any ideas?
You may be able to use "array_key_exists"
http://php.net/manual/en/function.array-key-exists.php
You may want to write a function but here is a solution using foreach.
$part_values = [];
$part_values_duplicates = [];
foreach($this->request->post['custom_parts'] as $customPart){
if(!in_array($customPart['part_value'], $part_values)){
$part_values[] = $customPart['part_value'];
}
else {
$part_values_duplicates[] = $customPart['part_value'];
}
}
var_dump($part_values_duplicates);

array_combine function is not displaying repeated values [duplicate]

This question already has answers here:
How can I loop through two arrays at once? [duplicate]
(2 answers)
Closed 6 years ago.
These are the values to be displayed.
print_r(array_values($price));
print_r(array_values($mec_id));
Array ( [0] => 3100 [1] => 1600 [2] => 1600 [3] => 3100 [4] => 7500 [5] => 3500 )
Array ( [0] => 47 [1] => 41 [2] => 42 [3] => 45 [4] => 46 [5] => 48 )
I need to use two arrays at a time in the foreach loop.
$combined_array = array_combine($price, $mec_id);
foreach($combined_array as $price=>$mec_id)
{
echo '<br>'.$mec_id.'-';
echo $price.'<br>';
}
But, after using array_combined method, it is combining the repeated values too. I think it is parsing the array from ending while combining.
45-3100
42-1600
46-7500
48-3500
You need to change order in array_combine so:
$combined_array = array_combine($mec_id, $price);
because you can not create the same index twice

PHP array in array - DXF script

I found a php script to write DXF file based on coordinates of polygon. IT works on the test file with this code (for polygon):
$d->append(new DxfPolyLine(array('points'=>array(array(1, 1),
array(20, 10),
array(20, 20),
array(1, 15)),
'lineType'=>'DASHED',
// 'layer' => 'DXFWRITER',
'flag' => 0
//'width' => 1,
//'color'=>1
)
));
The DXF file result is like this:
VERTEX
8
0
6
DASHED
10
20.000
20
20.000
0
VERTEX
8
0
6
DASHED
10
1.000
20
15.000
0
A lot of vertex's inside a polyline.
Now I am trying to insert my own coordinates. I have the coordinates but how can I write an array in that array?
I have this: $g=array_merge($g,array(array($coord[$z]*3.527785, $coord[$z+1]*3.527785)));
With this code the result is:
Array ( [0] => Array ( [0] => -133.92170714209 [1] => -41.834100838885 ) [1] => Array ( [0] => -135.19600658422 [1] => -44.558002415365 ) [2] => Array ( [0] => -173.40700872797 [1] => -25.465001344078 ) [3] => Array ( [0] => -211.44500829533 [1] => -6.4740001788315 ) [4] => Array ( [0] => -209.93490817601 [1] => -3.255100166471 ) [5] =>
Array ( [0] => -190.0770099388 [1] => -13.202000524885 ) [6] => Array ( [0] => -171.92300716209 [1] => -22.296000898041 ) [7] => Array ( [0] => -172.13500940166 [1] => -22.749000947663 ) [8] => Array ( [0] => -171.12900859213 [1] => -23.251001225378 ) [9] => Array ( [0] => -152.49300807866 [1] => -32.559001622754 ) [10] => Array ( [0] => -133.92170714209 [1] => -41.834100838885 ) )
So far so good. It respects the format from example. But in the DXF file does write only 1 (from array number).
If I change the code in
$d->append(new DxfPolyLine(array('points'=>array($g[3]),
with array[3] - it does write the coordinates in DXF file. Is there a way to make php to read all arrays from an array? I've tried with foreach but it doesn't work. PHP gives an error for not closing the ).
The source code is here:
https://github.com/digitalfotografen/DXFwriter
With $g[3] I have the coordinates from array[3] in DXF file:
VERTEX
8
0
6
CONTINUOUS
10
-211.445
20
-6.474
0
If I put $g simple I have:
VERTEX
8
0
6
CONTINUOUS
10
1.000
20
1.000
30
1.000
40
1.000
50
1.000
60
1.000
70
1.000
I recreated the $g array based on your dump. Does this outputs the desired DXF file?
$g = [[-133.92170714209, -41.834100838885],
[-135.19600658422, -44.558002415365],
[-173.40700872797, -25.465001344078],
[-211.44500829533, -6.4740001788315],
[-209.93490817601, -3.255100166471 ],
[-190.0770099388 , -13.202000524885],
[-171.92300716209, -22.296000898041],
[-172.13500940166, -22.749000947663],
[-171.12900859213, -23.251001225378],
[-152.49300807866, -32.559001622754],
[-133.92170714209, -41.834100838885]
];
$d->append(new DxfPolyLine(['points' => $g]));
regarding building the array, you could do something like this:
for ($z = 0; $z < $numar; $z+=2) {
$g[] = [$coord[$z]*3.527785,$coord[$z+1]*3.527785];
}
Your formatting's a bit screwy, but looking at the dumped array-data I see a single array who's values are arrays, that have 2 float values each. Note that Array[0] and Array[10] have the same values which may or may not be a problem for the lib.
Also, what's with the asterisks in the $d->append... logic?
Is there a way to make php to read all arrays from an array?
Yes, but PHP will impose some restrictions depending on the nature of the keys and values. See http://php.net/manual/en/language.types.array.php for more specific info as to how PHP treats arrays.
I've tried with foreach but it doesn't work. PHP gives an error for not closing the ).
Can you post the failing code please? What you describe is simply a formatting / syntax error and nothing to do with the data itself.

Handling PHP Array post values and merging - PHP Arrays

I know this won't take much time for experts here. But still please help me out
My Array output is like this
Array ( [0] => 1 [1] => 37 [2] => 1035 ) 1
Array ( [0] => 1 [1] => 37 [2] => 1035 ) mystatusmessage1
Array ( [0] => 4 [1] => 37 [2] => 2925 ) 2
Array ( [0] => 4 [1] => 37 [2] => 2925 ) mystatusmessage2
What I would like to get it is in a single string value like this so that I can insert into database.
1,37,1035,1,mystatusmessage1
4,37,2925,2,mystatusmessage2
How can I achieve that. I'm trying to do with foreach but still I'm not able to do it.
Thanks,
Kimz
use implode function to make string from array for example
if you have array like Array('a','b','c');
implode(',',array('a','b','c') )
will return a,b,c as string
here first argument is your glue by which you want to join string
Here you go.
// Original array
$array = array(0 => 1, 1 => 37, 2 => 1035);
// $_POST array
$_POST = array(1,'mystatusmessage1');
// Jump to the end of array
end($array);
// Merge the post with original array
$newArr = array_merge($array,$_POST);
// Impode
echo implode(",",$newArr);
Repeat with other array.

Categories