PHP - search multi dimesional array with multiple values - php

My function search inside a multi dimensional array for a match. It works but I would like to know if there is a better way to do that.
$arrays = array(
array('id' => 1, 'color_id' => 2, 'store_id' => 1),
array('id' => 1, 'color_id' => 2, 'store_id' => 2),
array('id' => 2, 'color_id' => 3, 'store_id' => 1)
);
function query_array($array, $keys = array(), $values = array()){
$match = array();
for($i = 0; $i < count($array); $i++){
for($x = 0; $x < count($keys); $x++){
if($array[$i][$keys[$x]] == $values[$x]){
$match[$i][] = 'increment';
if(count($match[$i]) == count($keys)){
return $array[$i];
}
}
}
}
return $match;
}
$searchKeys = array('item_id', 'store_id');
$searchValues = array(2,1);
$match = query_array($arrays, $searchKeys, $searchValues);
echo '<pre>';
print_r($match);
echo '<pre>';

Related

Adding numbers in a multidimensional array

Is there a faster way to add all the numbers in each segment of the multidimensional array rather than just doing it all manually? I was told before that a foreach loop could be used but I've hit a brick wall.
I'm trying to make it so it shows the total number of course enrollments in each campus and then the total number of students taking each course.
I feel like the answer is staring me in the face but I'm unsure.
<?
$campus = array();
$campus[1]['course1'] = 5; // <---- Number enrolled
$campus[1]['course2'] = 15;
$campus[1]['course3'] = 22;
$campus[1]['course4'] = 21;
$campus[1]['course5'] = 12;
$campus[1]['course6'] = 25;
$campus[1]['course7'] = 16;
$campus[1]['course8'] = 11;
$campus[1]['course9'] = 17;
$campus[1]['course10'] = 23;
$campus[2]['course1'] = 11;
$campus[2]['course2'] = 23;
$campus[2]['course3'] = 51;
$campus[2]['course4'] = 25;
$campus[2]['course5'] = 32;
$campus[2]['course6'] = 35;
$campus[2]['course7'] = 32;
$campus[2]['course8'] = 52;
$campus[2]['course9'] = 25;
$campus[2]['course10'] = 21;
$campus[3]['course1'] = 2;
$campus[3]['course2'] = 12;
$campus[3]['course3'] = 32;
$campus[3]['course4'] = 32;
$campus[3]['course5'] = 25;
$campus[3]['course6'] = 26;
$campus[3]['course7'] = 29;
$campus[3]['course8'] = 12;
$campus[3]['course9'] = 15;
$campus[3]['course10'] = 11;
echo "<pre>";
print_r($campus);
echo "<br/>";
foreach($campus as $key=>$value)
{
}
Use array_sum() to add the numbers in an array, and use array_map() to apply it to each element of the $campus array.
$total_by_campus = array_map('array_sum', $campus);
$courses = array();
foreach($campus as $key=>$value)
{
foreach($value as $course=>$num)
$courses[$course] += $num;
}
var_dump($courses);
Should do it.
You can use PHP's array_sum() function that will add up the values of the array you give it.
<?php
$sum = array_sum($campus[1]);
echo $sum;
$totcount = 0;
$count = array();
foreach($campus as $key=>$value)
{
foreach($value as $value1 => $value2)
{
$count[$value1]+=$value2;
$totcount++;
}
}
print_r($count);
echo "<br><br><br>". $totcount;
take a look:
$campus = array
(
'1' => array
(
'course1' => 5,
'course2' => 15,
'course3' => 22,
'course4' => 21,
'course5' => 12,
'course6' => 25,
'course7' => 16,
'course8' => 11,
'course9' => 17,
'course10' => 23,
),
'2' => array
(
'course1' => 11,
'course2' => 23,
'course3' => 51,
'course4' => 25,
'course5' => 32,
'course6' => 35,
'course7' => 32,
'course8' => 52,
'course9' => 25,
'course10' => 21,
),
'3' => array
(
'course1' => 2,
'course2' => 12,
'course3' => 32,
'course4' => 32,
'course5' => 25,
'course6' => 26,
'course7' => 29,
'course8' => 12,
'course9' => 15,
'course10' => 11,
),
);
foreach ($campus as $key0 => $value0)
{
// $key0 == (1, 2, 3)
// $value0 == array(course1 => 5, course2 => 15, course3 => 22, ...)
foreach ($value0 as $key1 => $value1)
{
// $key1 == (course1, course2, course3, ...)
// $value1 == (5, 15, 22, ...)
}
}
Sorry, but you post a question: "How to check an array's contents to see if they have any numbers?"
<?php
$cowboyfile = "COWBOY.TXT";
$data = array();
$data[] = "Colt Peacemaker, 12.20";
$data[] = "Holster, 2.00";
$data[] = "Levi Strauss Jeans, 1.35";
$data[] = "Saddle, 40.00";
$data[] = "Stetson, 10.00";
// Writing in the File
file_put_contents($cowboyfile, implode("\r\n", $data));
// Displaying all items above $10
$items = file($cowboyfile);
$item_filtred = array();
for ($i = 0; $i < count($items); $i++)
{
$item = $items[$i];
$item_price = substr($items[$i], strpos($item, ',') + 1);
if ($item_price >= 10)
{
$item_filtred[] = $item;
}
}
print_r($item_filtred);

How to change a multidimension array element with a function

I have an array like this:
<?php
$arr = [
'a' => [
'a1' => [
'A11', 'A12', 'A13'
]
]
];
I can change the A13 element in an easy way:
$arr['a']['a1'][2] = 'A13 NEW';
But I want to do this with a function, something like this:
f($arr, ['a', 'a1', 2], 'A13 New');
I write this function using eval and I don't like it.
<?php
function f(&$array, $index, $value) {
$e = '$array';
for ($i = 0, $l = count($index); $i < $l; $i++) {
$e .= '[$index[' . $i . ']]';
}
$e .= ' = $value;';
// now we have `$e` like this
// $array[$index[0]][$index[1]][$index[2]] = $value;
eval($e);
}
How can I write this function without using eval?
$arr = array(
'a' => array(
'a1' => array(
'A11', 'A12', 'A13'
)
)
);
function f(&$arr, $index, $value) {
$tmp = &$arr;
foreach ($index as $key) {
$tmp = &$tmp[$key];
}
$tmp = $value;
}
f($arr, array('a', 'a1', 2), 'A13 New');
//$arr['a']['a1'][2] = 'A13 NEW';
var_dump($arr);

How to get the uneven keys from an array?

I have to create a function that copy the array(that i pass to the function) with only uneven keys. Example:
$a = array(
'0' => '0',
'one => 'one',
'1' => '1',
'two' => 'two'
)
I have to get:
$result = array(
'one => 'one',
'two' => 'two'
)
I have created the follow function, it works, but maybe I need to optimize it(maybe exists a function that does this job). Advice?
private clean($values){
$vv = array();
$keys = array_keys($values);
for($i=1; $i < count($values); $i+=2) $vv[$keys[$i]] = $values[$keys[$i]];
return $vv;
}
Thanks
$even = range(0, count($array), 2);
source
UPDATE:
for ($i = 0, $c = count($array); $i <= $c; $i = $i + 2) {
$even = array_push($even, $array[$i]);
}
Try
$outputArray = array();
$keyToAdd = false;
foreach( $inputArray as $key => $value ) {
if( $keyToAdd ) {
$outputArray[$key] = $value;
}
$keyToAdd = !$keyToAdd;
}

PHP, Merging arrays with common keys

I need to get two arrays to merge into one while keeping all the keys in place and listing the values in an array like in this example:
$array1 = array('car' => '3', 'bus' => '2');
$array2 = array('dog' => '1', 'car' => '2', 'bird' => '9');
$merged = array(
'car' => array('3','2'),
'bus' => array('2',null),
'dog' => array(null,'1'),
'bird' => (null,'9')
);
function merge_common_keys(){
$arr = func_get_args();
$num = func_num_args();
$keys = array();
$i = 0;
for ($i=0; $i<$num; ++$i){
$keys = array_merge($keys, array_keys($arr[$i]));
}
$keys = array_unique($keys);
$merged = array();
foreach ($keys as $key){
$merged[$key] = array();
for($i=0; $i<$num; ++$i){
$merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
}
}
return $merged;
}
Usage:
$merged = merge_common_keys($array1,$array2);
PS. It can work with more than two arrays, just pass as many as you want as next arguments.
Something like this? http://php.net/array_merge_recursive

Check and return duplicates array php

I would like to check if my array has any duplicates and return the duplicated values in an array.
I want this to be as efficient as possible.
Example:
$array = array( 1, 2, 2, 4, 5 );
function return_dup($array); // should return 2
$array2 = array( 1, 2, 1, 2, 5 );
function return_dup($array2); // should return an array with 1,2
Also the initial array is always 5 positions long
this will be ~100 times faster than array_diff
$dups = array();
foreach(array_count_values($arr) as $val => $c)
if($c > 1) $dups[] = $val;
You can get the difference of the original array and a copy without duplicates using array_unique and array_diff_assoc:
array_diff_assoc($arr, array_unique($arr))
function array_dup($ar){
return array_unique(array_diff_assoc($ar,array_unique($ar)));
}
Should do the trick.
You can do like this:
function showDups($array)
{
$array_temp = array();
foreach($array as $val)
{
if (!in_array($val, $array_temp))
{
$array_temp[] = $val;
}
else
{
echo 'duplicate = ' . $val . '<br />';
}
}
}
$array = array(1,2,2,4,5);
showDups($array);
Output:
duplicate = 2
function returndup($array)
{
$results = array();
$duplicates = array();
foreach ($array as $item) {
if (in_array($item, $results)) {
$duplicates[] = $item;
}
$results[] = $item;
}
return $duplicates;
}
in addition to gumbo's answer:
function returndup($arr)
{
return array_diff_key($arr, array_unique($arr));
}
I did some tests and indeed #user187291's variant is the fastest. But, it turns out that #Gumbo's and #faebser's alternative are almost as fast, #faebser's being just slightly faster than #Gumbo's and sometimes even fastest of all.
Here's the code I used
$array = array(1, "hello", 1, "world", "hello");
$times = 1000000;
$start = microtime(true);
for ($i = 0; $i < $times; $i++) {
$dups = array();
foreach(array_count_values($array) as $val => $c)
if( $c > 1) $dups[] = $val;
}
$end = microtime(true);
echo 'variant 1 (user187291): ' . ($end - $start);
echo '<br><br><br>';
$start = microtime(true);
for ($i = 0; $i < $times; $i++)
$dups = array_unique(array_diff_assoc($array, array_unique($array)));
$end = microtime(true);
echo 'variant 2 (JAL): ' . ($end - $start);
echo '<br><br><br>';
$start = microtime(true);
for ($i = 0; $i < $times; $i++)
$dups = array_diff_assoc($array, array_unique($array));
$end = microtime(true);
echo 'variant 3 (Gumbo): ' . ($end - $start);
echo '<br><br><br>';
$start = microtime(true);
for ($i = 0; $i < $times; $i++)
$dups = array_diff_key($array, array_unique($array));
$end = microtime(true);
echo 'variant 4 (faebser): ' . ($end - $start);
echo '<br><br><br>';
I have found another way to return duplicates in an array
function printRepeating($arr, $size)
{
$i;
$j;
for($i = 0; $i < $size; $i++)
for($j = $i + 1; $j < $size; $j++)
if($arr[$i] == $arr[$j])
echo $arr[$i], " ";
}
printRepeating($array, sizeof($array,0);
If you need a solution that will work with an array of arrays (or any array values other than integers or strings) try this:
function return_dup( $arr ) {
$dups = array();
$temp = $arr;
foreach ( $arr as $key => $item ) {
unset( $temp[$key] );
if ( in_array( $item, $temp ) ) {
$dups[] = $item;
}
}
return $dups;
}
$arr = array(
array(
0 => 'A',
1 => 'B',
),
array(
0 => 'A',
1 => 'B',
),
array(
0 => 'C',
1 => 'D',
),
array(
0 => 'C',
1 => 'D',
),
array(
0 => 'E',
1 => 'F',
),
array(
0 => 'F',
1 => 'E',
),
array(
0 => 'Y',
1 => 'Z',
),
);
var_export( return_dup( $arr ) );
/*
array (
0 => array (
0 => 'A',
1 => 'B',
),
1 => array (
0 => 'C',
1 => 'D',
),
)
*/
As per your problem if you have duplicate values then you have to return those values. I write a function for this problem. If your array has duplicate values this function returns these values within the array otherwise it returns null values. Here is an example:
function containsDuplicate($array_values) {
$duplicates_values = [];
for($i = 0; $i < count($array_values); $i++){
for ($j=$i+1; $j <count($array_values) ; $j++) {
if ($array_values[$i] == $array_values[$j]) {
$duplicates_values[] = $array_values[$i];
}
}
}
if(count($duplicates_values) > 0){
return $duplicates_values;
}
}
$duplicate_array = array();
for($i=0;$i<count($array);$i++){
for($j=0;$j<count($array);$j++){
if($i != $j && $array[$i] == $array[$j]){
if(!in_array($array[$j], $duplicate_array)){
$duplicate_array[] = $array[$j];
}
}
}
}

Categories