How would i use array_intersect() with the arrays in an array? - php

I have a dynamic amount of arrays in a specific array.
Let's call this specific array: FatherArray
This FatherArray has a dynamic amount of arrays in it, right now for example: Child1Array,Child2Array. Next time it gets called it could have more or less than those 2 Child(number)Arrays.
So I want to use the function array_intersect() with the arrays (children) of FatherArray as parameters, so like array_intersect(Child1Array,Child2Array).
I don't have a clue how i could do this dynamically, neither could I find anything about it, any help would greatly be appreciated

If your version is reasonably new (v5.6):
array_intersect(...$FatherArray);
Otherwise:
call_user_func_array('array_intersect', $FatherArray);
Demo: see comment by Mark (thx #MarkBaker)

Related

PHP Sort Complex Array

Instead of working with mysql data, I have created csv file that I plan to use as the source of data for content, etc.
And I have successfully been able to parse the csv and store it into a complex array, that has the following header row aka the keys for the arrays.
"Title","Year","Rated","Released","Runtime","Genre","Director","Writer","Actors","Plot","Language","Country","Awards","Poster","Metascore","imdbRating","imdbVotes","imdbID","Type","Response"
My current stage is to allow dynamic ajax sorting of the arrays.
I have two fields, that I am allowing sorting at the beginning, "Year" and "Title".
So I pass different url paramters, such as "yearasc" or "yeardesc" or "titleasc" or "titledesc".
Then try to sort for that.
So what I did reading a different so post, was to do this.
First I create new arrays that only store the key fields, I need for sorting.
Then based on what sort type, do a different array_multisort.
array_multisort($year, SORT_ASC, $all_rows);
But what I get is results that multiple dupplicate data.
But I wonder if having the first row, be the header row, which is required by the function I pass the data after any sorting to, is causing issues with array sorting.
For simple array sorting, existing functions makes sense and work fine.
But for complicated ones, it is just complex to even understand how to approach solving this problem.
Any suggestions, thoughts or ideas are appreciated and thanked.
Thank you!
I don't have the actual code that is probably going to help you, but I do have a suggestion as for how you can tackle this and make it work..
Keep it simple. First, create your own CSV with just 1 header (Year or Title ) that you want to sort on.
Write your code to sort on that.
Then, add the other one ( Title if you used Year before, or Year if you used Title before ) and sort on whichever you want.
Then, add one more header (say, Rated) that you don't want to sort on.
You should then be able to work with the original CSV.
I'd try to write simple methods and keep your processing to a minimum in each one.
I hope that helps. I realize its more philosophical of an answer, so it is hit or miss if it helps you get the job done. Just realize that this approach will, indeed, take a little more time to write - but the point behind it is that you're taking out all of the "noise" that's getting in your way first. It helps you look at only your problem first and solve that.
You can set a custom sort function to the array. Use asort() if you need to keep original array keys.
<?php
$sortfields = array('year', 'bleh');
function cmp($a, $b) {
global $sortfields;
foreach ($sortfields as $sortfield) {
$cmp = strcmp($a[$sortfield], $b[$sortfield]);
// if desc, invert sign of $cmp
if ($cmp !== 0)
return $cmp;
}
return 0;
}
usort($all_rows, "cmp");
The function usort() calls a user defined comparison function, which returns the same logic from strcmp function: 0 if equal, < 0 is $a is less than $b and > 0 if $a is greater than $b.
This function will compare each field set in $sortfields variable, if it find any comparison that is different (in the order set), it will immediately return the difference.

Sorting array by values PHP

I am sorting through an array using the usort function. The loop is working correctly as is the sorting (to some degree) however I seem to have missed something with regards to decimal places etc. My function is below
usort($this->view->blogs, 'comparison');
And here is the function. The function call works correctly and I can see I am returned sorted data
function comparison($a, $b)
{
return strcmp($a->cost_per_blog, $b->cost_per_blog);
}
The issue is with the actual sorting logic for instance I am returned a list like below
0.09724
0.58344
1.16688
12.05776
120.5776
126.60648
13.22464
132.63536
138.66424
168.80864
18.08664
18.08664
18.67008
180.8664
19.25352
21.10108
22.26796
the pattern continues... It appears that I am not taking into account the sorting of 3 digit numbers. I cant seem to think of what I am missing. Any help would be greatly appreciated.
Don't compare strings then, compare numbers:
return $a->cost_per_blog - $b->cost_per_blog;
You compare them as strings not as doubles.

PHP - elegant (fast) way to access elements counting from end of array?

I've got an array where I want to grab the "negative three" element regardless of array length. (If that doesn't make sense throw out a comment and I'll clarify).
The obvious way to do it is $arr[count($arr)-4] but this feels clunky.
Is there a quick, elegant way to do this?
UPDATE
Still fiddling, any thoughts regarding this?
array_slice($arr,-4,-3);
The obvious way returns the single value you want in constant time, assuming you have numeric indexes. The array size is known to PHP already, it just jumps to the offset you want and gives you the result.
array_slice does many times as much work, comparing the array size to your offset, computing the loop conditions, creating a new array to store the slice, looping over the portion of the existing array, copying the values into the new array, then returning that array to you.
http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/standard/array.c
Yes there is:
Try something like this:
$newArray = array_slice($array, -3);
you could use $last = end($arr); then use prev($arr); twice to get 2 other elements.
Oh, and check if these return FALSE, in case you don't have at least 3 elements.
array_slice()?
array_slice($a, -3)
Try array_slice() function, giving negative offset as a second parameter.

Using an Array as the Key for an Array in PHP

I need to create an association between an Array and a Number; as PHP lacks a Map type, I am trying using an array to achieve this:
$rowNumberbyRow = array();
$rowNumberByRow[$rowData] = $rowNumber;
However, when I evaluate the code, I get the following Error:
Warning: Illegal offset type
Just to note, the data stored in the array ($rowData) does not have any 'unique' values that I can use as a key for the $rowNumberByRow Array.
Thanks!
UPDATE:
To answer some of my commenters, I am trying to create a lookup table so that my application can find the row number for a given row in O(1) time.
PHP does have a map Class: It's called SplObjectStorage. It can be accessed with exactly the same syntax as a general array is (see Example #2 on the reference).
But to use the class you will have to use the ArrayObject class instead of arrays. It is handled exactly the same way arrays are and you can construct instances from arrays (e.g. $arrayObject = new ArrayObject($array)).
If you don't want to use those classes, you can also just create a function that creates unique hash-strings for your indexes. For example:
function myHash($array){
return implode('|',$array);
}
$rowNumberByRow[myHash($array)] = $rowNumber;
You will of course have to make sure that your hashes are indeed unique, and I would strongly suggest you use the SplObjectStorage and maybe read a little bit more about the SPL classes of php.
Why not just store the row number in the array? e.g:
$rowData['rowNumber'] = $rowNumber;
You could instead serialize the array, e.g:
$rowNumberByRow[serialize($rowData)] = $rowNumber;
However that's pretty inefficient.
In php you can use only scalar values as an array keys.
If your $rowNumber is unique - then you'd try to use the opposite relation direction. If it is not unique - then you don't have any possible solution I know.
The answer has been alredy given and accepted, but while i was searching for a similar problem, i found this question, and i felt like i should drop a line: when someone wants to use an array with values as keys for another array, it would be useful to use the function array_combine.
If i got the arrays correctly, you could use:
$rowNumberByRow = array_combine($rowData, $rowNumber);
Please take a look at the PHP manual to see some info about permitted values for the keys :)

Using foreach to create grid

I am creating a grid in GD and was wondering if this is the right way to do it.
I have 2 arrays. One contains all X values, the other contains all Y values.
foreach ($xpointsArray as $xvalue) {
foreach ($ypointsArray as $yvalue) {
// Draw point at coordinates $xvalue, $yvalue
}
}
I just think there must be a more elegant way to set this up, and I would like to further
access the points values without doing this every time.
What you're doing is correct. There's possibly some more elegant solutions using a single two dimensional array, but either way you have to iterate through two loops.
Additionally, using a two dimensional array you could reference specific points by $Array[$x][$y] to get a specific point.
foreach, while, for are nice and I personally would prefer them, but since you are asking, what about using array_walk()?
array_walk($array1, "print_sudoku_field", $array2);

Categories