Where like queries on multidimensional arrays in php - php

Suppose I have a php array like this:
$shop = array( array("name"=>"Tom", "level"=> 1.25 ),
array("name"=>"Mike","level"=> 0.75 ),
array("name"=>"John","level"=> 1.15 )
);
I want to filter this array similar to filtering a mysql table with where conditions. Supposedly I want every array where level is higher than 1. I could iterate through and check with if statements. Are there any php solutions to this?

array_filter is what you are looking for:
$results= array_filter($shop, function($item) { return $item['level'] > 1; });
print_r($results);
Output:
Array
(
[0] => Array
(
[name] => Tom
[level] => 1.25
)
[2] => Array
(
[name] => John
[level] => 1.15
)
)

Related

merging array in CI 3

I want to merge two arrays in order to get the data as per my requirement.
I am posting my result, please have a look.
First array:
Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
)
)
Second array:
Array
(
[0] => Array
(
[user_id] => 9c2e00508cb28eeb1023ef774b122e86
[car_id] => 14783
[status] => favourite
)
)
I want to merge the second array into the first one, where the value at key car_id matches the equivalent value; otherwise it will return that field as null.
Required output:
<pre>Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
[fav_status] => favourite
)
)
Since the merge is so specific I would try something like this:
foreach ($array1 as $index => $a1):
foreach ($array2 as $a2):
if ($a1['car_id'] == $a2['car_id']):
if ($a2['status'] == "favourite"):
$array1[$index]['fav_status'] = "favourite";
endif;
endif;
endforeach;
endforeach;
You might be able to optimize the code more but this should be very easy to follow...
Another way to achieve this without using the index syntax is to reference the array elements in the foreach by-reference by prepending the ampersand operator:
foreach($firstArray as &$nestedArray1) {
foreach($secondArray as $nestedArray2) {
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1['fav_status'] = $nestedArray2['status'];
}
}
}
You can see it in action in this Playground example.
Technically you asked about merging the arrays. While the keys would be different between the input arrays and the desired output (i.e. "status" vs "fav_status"), array_merge() can be used to merge the arrays.
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 = array_merge($nestedArray1, $nestedArray2);
}
Playground example.
Additionally the union operators (i.e. +, +=) can be used.
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator1
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 += nestedArray1;
}
Playground example.
1http://php.net/manual/en/function.array-merge.php#example-5587

Intersect (inner join) two arrays with different key names

I have following two multidimensional arrays:
First array:
$array_1_data = Array (
[0] => Array ( [id] => 1 [name] => IT [slug] => it )
[1] => Array ( [id] => 2 [name] => Accounting [slug] => accounting )
)
Second array:
$array_2_data = Array (
[0] => Array ( [cid] => 3 [jid] => 24061 )
[1] => Array ( [cid] => 1 [jid] => 24062 )
)
Expected result:
$some_array = Array (
[0] => Array ( [id] => 1 [name] => IT [slug] => it )
)
I won't mind having [cid] in the result.
I want to intersect these two arrays by [id] of the first array and [cid] of the second array, like inner join in MySQL. I have basic foreach and if else logic for this purpose but speed is a priority now so I'm looking for non-looped solution. For better understanding here is the basic looped solution:
foreach ($array_1_data as $array_1_row ) {
foreach ($array_2_data as $array_2_row ) {
if ($array_2_row['cid'] == $array_1_row['id']) {
//intersection iteration
}
}
}
I tried array_uintersection as follows:
array_uintersect($array_1_data, $array_2_data, function($a1, $a2){
$diff1 = strcasecmp($a1['id'], $a2['cid']);
if ($diff1 != 0) return $diff1;
return 0;
});
But it gives me undefined index 'id'. I checked this question: Comparing two arrays with different key names. First answer for this question gives a looped solution which I want to avoid. Second answer suggests changing SQL structure but I have no control over that. So,
Is there really a non-looped fast solution to this kind of situation?
The solution using array_uintersect_uassoc function:
$result = array_uintersect_uassoc($array_1_data, $array_2_data, function($a, $b){
return strcasecmp($a['id'], $b['cid']);
}, function($a, $b){
return (int) [$a, $b] == ['id', 'cid'];
});
print_r($result);
The output:
Array
(
[0] => Array
(
[id] => 1
[name] => IT
[slug] => it
)
)
According yo your condition: to intersect these two arrays by [id] of the first array and [cid] of the second array, we should consider a key comparison function for those keys only ['id', 'cid'].
Having the needed keys on each comparison step it only remain to compare their values(with value compare function)
http://php.net/manual/en/function.array-uintersect-uassoc.php
DEMO link

Sorting in php Arrayss

My sql table consists of ID,Book name,Genre and ratings.Currently my array from my sql table looks like this (output)
Array (
[book] => Array (
[0] => Array
( [0] => 1
[1] => book one
[2] => Fantasy/Horror
[4] => 8.9 )
[1] => Array (
[0] => 2
[1] => book two
[2] => Comedy
[4] => 8.3 ) ) )
i want to sort this array to DESC by ID
Also in the future by title.
The array variable is $book so i wrote ksort($book) also tried arsort
for some reason it doesnt work? Is it because of the array? Thanks!
IF you are able to:
Use SQL sorting instead, because of the speed and flexibility (Use db-engine where it's appropiate) Only use array-functionality if you really need to! :-)
Do something like:
SELECT ID,Book name,Genre, ratings ORDER BY ID DESC
OR
If you have still have to use array sorting, use usort() in PHP:
<?php
//Book array
$bookArray['book'][0] = array(2, 'book one', 'Fantasy/Horror', 8.9);
$bookArray['book'][1] = array(1, 'book two ', 'Comedy', 8.3);
function sortByIndex($a, $b) {
return $a[0] - $b[0];
}
usort($bookArray['book'], 'sortByIndex');
echo 'RESULT=' . print_r($bookArray,true);
?>
Results in this output:
RESULT=Array ( [book] => Array ( [0] => Array ( [0] => 1 [1] => book two [2] => Comedy [3] => 8.3 ) [1] => Array ( [0] => 2 [1] => book one [2] => Fantasy/Horror [3] => 8.9 ) ) )
Book two comes first here, because in my example I set the first index to be 1 with value 'book two'.
The easiest way is to add this to your SQL statement at the end:
ORDER BY id DESC
Also if you really want to know how to do it in PHP you would do it this way:
function cmp($a, $b)
{
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] > $b[0]) ? -1 : 1;
}
usort($array['book'], "cmp");
Just you need to change your Select Statement. It should be something like this -
select id,bookname,genre,ratings from yourtable ORDER BY id DESC,bookname;

Array_Unique filtering

I have an multidimensional array:
Array
(
[0] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Other Cereals
[IName] =>
[Date] => 2013-02-05
)
[1] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar
[Date] => 2013-02-06
)
[2] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
[Date] => 2013-02-05
)
)
And I am trying to use array unique to filter this
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
I am having no luck. How can I filter the duplicates?
Cheers.
If you filter input and therefore don't have extra spaces in IName field, you can use something as simple as this for filtering:
$array[2]['IName'] = implode(',', array_unique(explode(',', $array[2]['IName'])));
The problem is that you habe in array two Oats,Milk,Sugar as element of IName, in array three you have Oats,Milk,Sugar,Oats,Milk,Sugar. This is not the same!
"Oats,Milk,Sugar"=="Oats,Milk,Sugar,Oats,Milk,Sugar" (or "Oats,Milk,Sugar".equals("Oats,Milk,Sugar,Oats,Milk,Sugar")) is false.
If you want to have it unique you have to explode the single results and then do a unique on it or you have to store the single values in seperate fields...
BTW: Here is a link how to remove duplicates from a multi dimensional array How to remove duplicate values from a multi-dimensional array in PHP
I am not sure if a function exists for that, here is a simple solution,
you can loop the array, and get the result of each value, then explode result, and insert it into an array.
then use the array_unique function.
try this:
$result = array();
foreach($arrays as $array)
{
$tmp = $array['IName'];
$tmp2 = explode(',',$tmp);
foreach ($tmp2 as $t)
{
$result[]=$t;
}
}
$array_unique = array_unique($result);

calculations between two Multidimensional arrays

I have this code:
$id = new matrix(array(0=>array(1,0.5,3), 1=>array(2,1,4), 2=>array(1/3,1/4,1)));
$soma = $id->times($id)->sumRows();
That outputs this:
matrix Object ( [numbers] => Array ( [0] => Array ( [0] => 12.75 [1] => 22.3333333333 [2] => 4.83333333333 ) ) [numColumns] => 3 [numRows] => 1 )
and:
$total = $id->times($id)->sumRows()->sumTotal($id);
That outputs this:
matrix Object ( [numbers] => Array ( [0] => Array ( [0] => 39.9166666667 ) ) [numColumns] => 3 [numRows] => 1 )
Now, i am trying to make:
foreach ($soma as $value){
$final = (int)$value/(int)$total;
print_r ((int)$final);
}
The output will be 000.
Must be:
12.75/39.9166666667 = 0,3269230769230769
22.3333333333 / 39.9166666667 = ...
and so on
Thanks!
Just some ideas, without really knowing much about the matrix class...
All those (int)s should probably be (float)s, as you seem to want a non-int answer.
$value is itself an object, so you'll probably need to use $value['numbers'][0][0 or 1 or 2]. Same goes for $total.
the issue is solved :
documentation:
get_data($..)

Categories