In php, i am new in php anybody help me for this?
i have two arrays , in Array2 i have two records, i want to check Data of Array2 whether in Array1 or not , how can i check the data of Array2 in Array1 its available or not !
Thanks in advance
Array1
[items] => Array
(
[0] => Array
(
[abc] => z1
[xyz] => cool
[val] => 2.32
[color] => D
)
[1] // i have 5o records in array1
);
Array 2
[items] => SearchArray
(
[0] => Array
(
[abc] => z1
[xyz] => cool
[val] => 2.32
[color] => D
)
[1] // i have 2 records
);
Please try this code - I hope it helpes some way :
$matches = array();
for($i2 = 0; $i2 < count($Array2); $i2++)
{
for($i1 = 0; $i1 < count($Array1); $i1++)
{
$bMatch = TRUE;
foreach($Array1[$i1] as $key => $val)
{
if($Array2[$i2][$key] !== $val)
{
$bMatch = FALSE;
break;
}
}
if($bMatch)
{
$matches[] = array($i2, $i1);
}
}
}
It iterates through both arrays, comparing elements (which in fact are sub arrays) in such way that they are equal only if all elements of sub array from $Array2 are equal to all elements of sub array from $Array1. If the match is found, the pair ($i2, $i1) is added to the $matches array, so in the end, basing on your example, you would have something like:
$matches => array (
[0] => array (0, 0)
...
)
I hope the assumption made is the proper one.
Can use array_search method. For more information, check out the manual reference: http://php.net/manual/en/function.array-search.php
Related
Lets say I have an array of numbers: [1,2,3].
How can I loop through this array to create an array of possible permutations.
I'm expecting outputs like:
[1,2], [1,3], [2,1], [2,3], [3,1], [3,2].
Simple nested loops required for the same input array
Do the following:
$input = array(1,2,3);
$output = array();
// to get all possible permutations
// for first value in the permutation, loop over all array values
foreach ($input as $value1) {
// for second value in the permutation, loop again similarly
foreach ($input as $value2) {
if ($value1 !== $value2) // dont consider same values
$output[] = array($value1, $value2);
}
}
If i understand the question correctly, you want to have an array containing X amount of integers and get every possible combination of two distinct integers from that array?
This can be done with two for loops, one to loop through each of your array's elements, and another that combines that element with every other element.
for(int $x = 0; $x < count($arr1); $x++) {
for(int $y = 0; $y < count($arr1); $y++) {
if ($x == $y || $arr1[$x] == $arr1[$y]) {
continue;
} else {
array_push($output, [$arr1[$x], $arr1[$y]]);
}
}
}
Looking at your example I assumed you don't want repeating numbers. So I did a loop with an inner loop and compared the numbers before adding to the print Array! My first stackoverflow submissions so I'd love some feedback!
$arrayToParse = [1, 2, 3];
$arrayToPrint = [];
foreach($arrayToParse as $num1){
foreach($arrayToParse as $num2){
if($num1 != $num2){
array_push($arrayToPrint, [$num1, $num2]);
}
}
}
print_r($arrayToPrint);
// OUTPUT
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 2
[1] => 1
)
[3] => Array
(
[0] => 2
[1] => 3
)
[4] => Array
(
[0] => 3
[1] => 1
)
[5] => Array
(
[0] => 3
[1] => 2
)
)
I have an multidimensional array from an XML file which I want to compare with a normal array. I need to compare the [tag] name in the multidimensional array with the name in the other array and get value from the multidimensional array that belongs to the tag.
Array
(
[0] => Array
(
[tag] => DOCUMENT
[type] => open
[level] => 1
)
[1] => Array
(
[tag] => SENDERID
[type] => complete
[level] => 2
[value] => TEST
)
[2] => Array
(
[tag] => SENDERSHORTNAME
[type] => complete
[level] => 2
)
[3] => Array
(
[tag] => RECIPIENTID
[type] => complete
[level] => 2
[value] => VGLEE
)
)
Second array which I need to compare it with the multidimensional array:
$compare_array = array('DOCUMENT', 'SENDERID', 'SENDERSHORTNAME', 'RECIPIENTID');
Now I want to check if the key from $compare_array is matched in the multidimensional array. If so, I want to grab the value from the multidimensional array and make a variable with the name from the compare_array and append the value to the variable.
I made a for loop:
for($i = 0; $i < $count; $i++){
if($values[$i]['tag'] == 'SENDERID'){
$SENDER = $values[$i]['value'];
}
if($values[$i]['tag'] == 'RECIPIENTID'){
$RECIPIENTID = $values[$i]['value'];
}
if($values[$i]['tag'] == 'IREF'){
$IREF = $values[$i]['value'];
}
if($values[$i]['tag'] == 'DOCUMENTNUMBER'){
$DOCUMENTNUMBER = $values[$i]['value'];
}
}
For your example data, you could use array_reduce and use in_array to check if the tag is present in $compare_array
If you must make a variable with the name from the $compare_array and append the value to the variable you might use extract with a flag that suits your expectations.
The value is not present in all the example data so you might also check if that exists.
$compare_array = array('DOCUMENT', 'SENDERID', 'SENDERSHORTNAME', 'RECIPIENTID');
$result = array_reduce($arrays, function($carry, $item) use ($compare_array) {
if(isset($item["value"]) && in_array($item["tag"], $compare_array, true)) {
$carry[$item["tag"]] = $item["value"];
}
return $carry;
});
extract($result, EXTR_OVERWRITE);
echo $SENDERID;
echo $RECIPIENTID;
Demo
You can try using array_in() in this case, below is the sample code
for($i = 0; $i < $count; $i++){
if(in_array($values[$i]['tag'],$compare_array)){
$value = $values[$i]['value'];
}
}
For reference in_array()
Try following code:
$array = []; //Complete array to be parsed.
$compare_array = array('DOCUMENT', 'SENDERID', 'SENDERSHORTNAME', 'RECIPIENTID');
foreach ($array as $value) {
if (in_array($value["tag"], $compare_array)) {
$$value["tag"] = $value["value"];
}
}
It will traverse through array and if tag name matched to value $compare_array, then define a variable with tag name and initialize with value.
I have this php array named $ids:
Array (
[0] => Array ( [id] => 10101101 )
[1] => Array ( [id] => 18581768 )
[2] => Array ( [id] => 55533322 )
[3] => Array ( [id] => 55533322 )
[4] => Array ( [id] => 64621412 )
)
And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.
Something like this:
$newArr = array(
10101101 => 1,
18581768 => 1,
55533322 => 2,
64621412 => 1,
);
This is what I have:
$newArr = array();
$aux1 = "";
//$arr is the original array
for($i=0; $i<count($arr); $i++){
$val = $arr[$i]["id"];
if($val != $aux1){
$newArr[$val] = count(array_keys($arr, $val));
$aux1 = $val;
}
}
I supose array_keys doesn't work here because $arr has the id values in the second dimension.
So, how can I make this work?
Sorry for my bad english and thanks.
array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.
$newArr = array_count_values(array_column($ids, 'id'));
Or do it by hand like this where $arr is your source array and $sums is your result array.
$sums = array();
foreach($arr as $vv){
$v = $vv["id"];
If(!array_key_exists($v,$sums){
$sums[$v] = 0;
}
$sums[$v]++;
}
You can traverse your array, and sum the id appearance, live demo.
$counts = [];
foreach($array as $v)
{
#$counts[$v['id']] += 1;
}
print_r($counts);
How can I count in a multidimensional array the number of element with a special condition ?
Array
(
[0] => Array
(
[item] => 'Banana'
)
[1] => Array
(
[item] => 'Banana'
)
[2] => Array
(
[item] => 'Cherry'
)
[3] => Array
(
[item] => 'Apple'
)
)
For example, for this array I should find 2 for Banana.
Si I tried:
$i=0;
foreach($array as $arr) {
if($arr[item]=='Banana') { $i++; }
}
Is there a better solution please ?
Thanks.
Method 1:
Using built-in functions - array_column and array_count_values:
print_r(array_count_values(array_column($arr,'item')));
Method 2:
Using foreach with simple logic of making your fruit as key and its count as value:
$arr = [
["item"=>"Banana"],
["item"=>"Banana"],
["item"=>"Cherry"],
["item"=>"Apple"]
];
$countArr = [];
foreach ($arr as $value) {
$item = $value['item'];
if(array_key_exists($item, $countArr)) // If key exists, increment its value
$countArr[$item]++;
else // Otherwise, assign new key
$countArr[$item] = 1;
}
print_r($countArr);
Final result in both case would be:
Array
(
[Banana] => 2
[Cherry] => 1
[Apple] => 1
)
So when you want Banana's count, you can get it like this:
echo $countArr['Banana'];
Use array_count_values(), it is pretty straight forward:
foreach($array as $arr) {
$new[] = $arr['item'];
}
print_r(array_count_values($new));
On a side note, there isn't anything wrong with your approach, unless you want to count all values. Also on a side note, I think you'll find a foreach() will eek out a slightly faster time than array_column(), especially on a large array.
I have the array:
$total =array();
Array (
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
)
)
I need to dynamically change each array into an indexed array for a Cartesian function.
Here is how I need the code to look for the function to work correctly:
$count = cartesian(
Array(1,3),
Array(6,7,8),
Array(9,10)
);
Any help would be greatly appreciated! I have tried flattening, looping, using array_values, using just the array itself and I keep falling short.
Thanks
Nick
function cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
$count = call_user_func('cartesian', array($total));
print_r($count);
Your arrays already look exactly the way you want them to. array(1,3) is the same as array(0 => 1, 1 => 3) and both are an array with the value 1 at key 0 and 3 at key 1. Exactly what the debug output shows you.
It seems you just need to pass them as separate arguments to the function. E.g.:
cartesian($total[0], $total[1], $total[2])
For dynamic lengths of arrays, do:
call_user_func_array('cartesian', $total)
I believe that your $total array is multi-dimensional array with numeric indexed. So yo can try like this
$count = cartesian($total[0], $total[1], $total[2]);