PHP: search for values in the array and display the key - php

I have array with the structure as below.
Array
(
[example1] => Array
(
[0] => 'banana'
)
[example2] => Array
(
[0] => 'orange'
[1] => 'apple'
[2] => 'plum'
[3] => 'watermelon'
[4] => 'pumpkin'
)
[example3] => Array
(
[0] => 'cherry'
[1] => 'strawberry'
)
)
I am trying to display the key name for a sample value.
Eg.
looking for a value: 'apple' - result: 'example2'

Simply loop your arrays and check if element exists:
function search(string $search, array $source) {
foreach ($source as $key => $sub) {
if (in_array($search, $sub)) {
return $key;
}
}
}
search('apple', $source);

Just iterate thru all the subarrays and return the parent key.
$array = [
'example1' => ['banana'],
'example2' => ['orange', 'apple', 'plum', 'watermelon', 'pumpkin'],
'example3' => ['cherry', 'strawberry']
];
$needle = 'apple';
$result = '';
foreach($array as $parentKey => $child) {
if(in_array($needle, $child)) {
$result = $parentKey;
break;
}
}
echo $result;
example2

that's a good example too, thanks.
I built my function on this basis
function CheckArray($my_array,$search) {
$result = array_keys(array_filter($my_array, function ($arr) use ($search) {
return in_array($search, $arr);
}));
if(isset($result[0])){
return $result[0];
}else{
return "not find";
}
}

Related

Search with in_array_r returns wrong result

I am trying to find value in multidimensional array using recursive in_array function, but I always get not found.
This is the structure of array $v :
Array
(
[0] => Array
(
[EV000005] => Array
(
[0] => Array
(
[0] => Array
(
[0] => EN
[1] => Thread holding
)
[1] => Array
(
[0] => nl-NL
[1] => Schroefdraadhouder
)
)
)
)
This is function:
public function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
And this is how I call function which echoes to me not found instead of found:
echo $this->in_array_r("EV000005", $v) ? 'found' : 'not found';
I also tried to use $strict = true but same result.
Why is the search for EV000005 unsuccessful in this case?
Reference from link.
You are searching recursively for value, but in example you are trying to search it by key.
You can use this function to achieve this,
function array_key_exists_custom($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result) {
return $result;
}
foreach ($haystack as $v) {
if (is_array($v)) {
$result = array_key_exists_custom($needle, $v);
}
if ($result) {
return $result;
}
}
return $result;
}
Here is working demo.
Here is object oriented working demo as per requirement.
Here is your code :
<?php
//Enter your code here, enjoy!
class A
{
public function array_key_exists_custom($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result) {
return $result;
}
foreach ($haystack as $v) {
if (is_array($v)) {
$result = $this->array_key_exists_custom($needle, $v);
}
if ($result) {
return $result;
}
}
return $result;
}
public function getData()
{
$arr = array
(
"0" => array
(
"EV000005" => array
(
"0" => array
(
"0" => array
(
"0" => "EN",
"1" => "Thread holding",
),
"1" => array
(
"0" => "nl-NL",
"1" => "Schroefdraadhouder",
),
),
),
),
);
$temp = $this->array_key_exists_custom("EV000005", $arr);
echo ($temp ? "found" : "not found");
}
}
$obj = new A;
$obj->getData();
?>
Try this, your array should be:
Array
(
[0] => Array
(
["EV000005"] => Array
(
[0] => Array
(
[0] => Array
(
[0] => "EN"
[1] => "Thread holding"
)
[1] => Array
(
[0] => "nl-NL"
[1] => "Schroefdraadhouder"
)
)
)
)
)
in_array_r searches for values, but you are looking vor a key.
try this gist

Delete the indexes of elements which exists more than once in an array php

I have the following array,
Array
(
[0] => 5600
[1] => 5600
[2] => 5500
[3] => 5500
[4] => 5003
[5] => 5002
[6] => 5001
[7] => 768
[8] => 768
[9] => 767
[10] => 730
[11] => 666
[12] => 575
)
Now I want to delete the indexes of elements which exists more than once in an array. For example I want the above given array like this.
Array
(
[0] => 5003
[1] => 5002
[2] => 5001
[3] => 767
[4] => 730
[5] => 666
[6] => 575
)
Share your ideas if any one has the key.
<?php
// sample input
$arr = array(1,1,2,2,2,3,4,5);
// input
print_r($arr);
// to retain keys
print_r(
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
);
// to reset keys using array_values
print_r(
array_values(
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
)
);
?>
Test results
akshay#db-3325:/tmp$ php test.php
Array
(
[0] => 1
[1] => 1
[2] => 2
[3] => 2
[4] => 2
[5] => 3
[6] => 4
[7] => 5
)
Array
(
[5] => 3
[6] => 4
[7] => 5
)
Array
(
[0] => 3
[1] => 4
[2] => 5
)
Eliminate repeating values with array_unique, restore indexes with array_values:
print_r(array_values(array_unique($arr)));
Update:
$new = [];
foreach (array_count_values($arr) as $k => $v) {
if ($v == 1) {
$new[] = $k;
}
}
As a oneliner with array_filter (since php5.6):
$new = array_filter(
array_count_values($arr), function($v, $k) {
return $v == 1;
},
ARRAY_FILTER_USE_BOTH
);
Thank you for the question. Mine is not a nice solution. I used your question to make a little exercise of test driven development.
use PHPUnit\Framework\TestCase;
final class RemoveNonUniqueItemsTest extends TestCase
{
public function testEmptyArrayReturnEmptyArray()
{
$uniqueItems = Remover::keepOnlyUnique([]);
$this->assertEquals(
[],
$uniqueItems->asArray()
);
}
public function testArrayWithUniqueKeysReturnSameArray()
{
$uniqueItems = Remover::keepOnlyUnique([1,2,3]);
$this->assertEquals(
[1,2,3],
$uniqueItems->asArray()
);
}
public function testCountNumnerOfItemsAValueAppears()
{
$uniqueItems = Remover::keepOnlyUnique([1,2,3,3]);
$this->assertEquals(
2,
$uniqueItems->items(3)
);
}
public function testRemoveValuesThatExistsTwice()
{
$uniqueItems = Remover::keepOnlyUnique([1,2,3,3]);
$this->assertEquals(
[1,2],
$uniqueItems->asArray()
);
}
}
final class Remover
{
private $items;
private function __construct(array $items)
{
$this->items = $items;
}
public static function keepOnlyUnique(array $items) : Remover
{
return new self($items);
}
public function asArray() : array
{
$newArray = [];
foreach ($this->items as $itemKey => $itemValue) {
if ($this->items($itemValue) == 1) {
$newArray[] = $itemValue;
}
}
return $newArray;
}
public function items(int $value) : int
{
$count = 0;
foreach ($this->items as $itemKey => $itemValue) {
if ($itemValue == $value) {
$count++;
}
}
return $count;
}
}
Using simple loops.
Count how many times each value occurs. And then loop through these frequencies. If the value only occurs once add to our desired array.
<?php
function only_unique(array $values) {
$result = $freq = array();
foreach($values as $value)
isset($freq[$value]) ? $freq[$value]++ : $freq[$value] = 1;
foreach($freq as $key => $value)
if($value == 1)
$result[] = $key;
return $result;
}
$nums = [1,2,2,3,3,3,4];
var_dump(only_unique($nums));
Output:
array(2) {
[0]=>
int(1)
[1]=>
int(4)
}
The above is similar to below:
$desired =
array_keys(
array_filter(
array_count_values($nums), function($v) {
return $v == 1;
}
)
);
Almost every Answer offered here is right.... but then, again... here's another one:
<?php
$arr = [
5600, 5600, 5500, 5500, 5003, 5002,
5001, 768, 768, 767, 730, 666, 575,
];
function arraySansDuplicates($array){
$result = [];
foreach($array as $value){
if(!in_array($value, $result)){
$result[] = $value;
}else{
$key = array_search($value, $result);
unset($result[$key]);
}
}
return array_values($result);
}
var_dump( arraySansDuplicates($arr) );

How to convert multi-dimensional array into single array using PHP?

After implementing database queries, I am getting the multi-dimensional array below.
Two Dimensional Array
Array
(
[0] => Array
(
[t1] => test1
)
[1] => Array
(
[t2] => test2
)
[2] => Array
(
[t3] => test3
)
[3] => Array
(
[t4] => test4
)
[4] => Array
(
[t5] => test5
)
)
but I want to convert it to a single dimensional array, like the format below:
One Dimensional Array
Array (
t1 => test1
t2 => test2
t3 => test3
t4 => test4
t5 => test5
)
How can I do this?
I think you can use array_reduce() function.
For example:
$multi= array(0 => array('t1' => 'test1'),1 => array('t2' => 'test2'),2 => array('t3' => 'test3'),3 => array('t4' => 'test4'));
$single= array_reduce($multi, 'array_merge', array());
print_r($single); //Outputs the reduced aray
You can use as follows :
$newArray = array();
foreach($arrayData as $key => $value) {
foreach($value as $key2 => $value2) {
$newArray[$key2] = $value2;
}
}
Where $arrayData is your DB data array and $newArray will be the result.
Assuming that source array is array of arrays and it has no the same keys:
<?php
$src = [
['t1'=>'test1'],
['t2'=>'test2'],
['t3'=>'test3'],
['t4'=>'test4'],
['t5'=>'test5'],
];
$result = call_user_func_array('array_merge', $src);
result via var_dump():
array(5) {
["t1"]=>
string(5) "test1"
["t2"]=>
string(5) "test2"
["t3"]=>
string(5) "test3"
["t4"]=>
string(5) "test4"
["t5"]=>
string(5) "test5"
}
You can use array_reduce() to change values of array. In callback get key of item using key() and select first item using reset().
$newArr = array_reduce($oldArr, function($carry, $item){
$carry[key($item)] = reset($item);
return $carry;
});
Check result in demo
Try this function,
function custom_function($input_array)
{
$output_array = array();
for ($i = 0; $i < count($input_array); $i++) {
for ($j = 0; $j < count($input_array[$i]); $j++) {
$output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
}
}
return $output_array;
}
$arr = custom_function($arr);
print_r($arr);
Give it a try, it will work.
You can use this
<?php
$temp = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result_array = array();
foreach ($temp as $val) {
foreach ($val as $key => $inner_val) {
$result_array[$key] = $inner_val;
}
}
print_r($result_array);
?>
// Multidimensional array
$arrdata = Array(
'0' => Array(
't1' => 'test1'
) ,
'1' => Array(
't2' => 'test2'
) ,
'2' => Array(
't3' => 'test3'
)
);
// Convert to a single array
$data = array();
foreach($arrdata as $key => $value) {
foreach($value as $key1 => $value1) {
$data[$key1] = $value1;
}
}
echo $data;
Try array map function.
$singleDimensionArray = array_map('current',$multiDimensionArray);
You can use this if you don't care about keeping the correct array keys
function flattenA(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
print_r(flattenA($arr));
// Output
Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
[4] => test5
)
Otherwise
function flattenB(array $array) {
$return = array();
array_walk_recursive($array, function($v,$k) use (&$return) { $return[$k] = $v; });
return $return;
}
print_r(flattenB($arr));
// Output
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
Check both on Sandbox
From answer on similar question
For your specific case, I would use array_reduce where I set the initial value with an empty array
array_reduce($arr, function($last, $row) {
return $last + $row;
}, array());
AFTER PHP 7.4
array_reduce($arr, fn ($last, $row) => $last + $row, []);
Result :
[
't1' => 'test1',
't2' => 'test2',
't3' => 'test3',
't4' => 'test4',
't5' => 'test5'
]
Hey #Karan Adhikari Simple like below one:
<?php
$arr1 = array(array("t1" => "test1"), array("t2" => "test2"), array("t3" => "test3"), array("t4" => "test4"), array("t5" => "test5"));
echo "<pre>";
print_r($arr1);//before
$arr2 = array();
foreach($arr1 as $val){
$arr2 = array_merge($arr2, $val);
}
echo "<pre>";
print_r($arr2); // after you get your answer
Please try this function:
function array_merging($multi_array) {
if (is_array($multi_array)) {
$new_arr = array();
foreach ($multi_array as $key => $value) {
if (is_array($value)) {
$new_arr = array_merge($new_arr, array_merging($value));
}
else {
$new_arr[$key] = $value;
}
}
return $new_arr;
}
else {
return false;
}
}
Use this function:
$your_multi_arr = array(array(array('t1'=>'test1'),array('t2'=>'test2'),array('t3'=>'test3'),array('t4'=>'test4')));
$arr1 = array_merging($your_multi_arr);
echo "<pre>";
print_r($arr1);
Hope, this may be useful for you.
You can try traversing the array using PHP while list and each. I took sample code from PHP website the second example you can check it here
$arr = [['t1' => 'test1'],['t2' => 'test2'],['t3' => 'test3'],['t4' => 'test4'],['t5' => 'test5']];
$output = [];
while (list($key, $val) = each($arr)) {
while (list($k, $v) = each($val)) {
$output[$k] = $v;
}
}
print_r($output);
Output created is
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
You can test it on your own in this Sandbox example.
This will do the trick
$array = array_column($array, 't1');
Note: This function array_column introduced in PHP 5.5 so it won't work in earlier versions.
traverse the array and save the key value, Live Demo here.
<?php
$array = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result = [];
array_walk($array, function($value) use(&$result){
foreach($value as $k => $v)
{
$result[$k] = $v;
}
});
var_dump($result);
`$result = "Query"; $key_value = array();`
foreach ($result as $key => $value) {
$key_value[$key['']] = $value[''];
}
//for checking //echo "<pre>" ; print_r($key_value) ; exit;
return $key_value;
pls fill $key['name given in sql query for field'] and $value['name given in sql query for field'] (both are same)
this works for me
$result = [];
foreach($excelEmails as $arr)
{
foreach ($arr as $item){
$result = array_merge($result , $item);
}
}
dd($result);
i would recomment my way to convert all double-dimensional array to single-dimensional array.
<?php
$single_Array = array();
//example array
$array = array(
array('t1' => 'test1'),
array('t2' => 'test2'),
array('t3' => 'test3'),
array('t4' => 'test4'),
array('t5' => 'test5'));
$size = sizeof($array);
//loop to fill the new single-dimensional array
for($count = 0; $count<sizeof($array);$count++)
{
//take the key of multi-dim array
$second_cell = key($array[$count]);
//set the value into the new array
$single_array[$count] = $array[$count][$second_cell];
}
//see the results
var_dump($single_array);
?>
with this script we can take keys and values to create new single-dimensional array.I hope that i was helpfull to you.
you can see the example here: Array Convert Demo

Remove items from multidimensional array in PHP

I need to remove empty items in a multidimensional array.
Is there a simple way I can remove the empty items easily?
I need to keep only 2010-06 and 2010-07.
Thank you very much!
Array
(
[2010-01] => Array
(
[2010-03] => Array
(
[0] =>
)
[2010-04] => Array
(
[0] =>
)
[2010-06] => Array
(
[0] => stdClass Object
(
[data_test] => value
[date] => 2010-05-01 12:00:00
)
)
[2010-07] => Array
(
[0] => stdClass Object
(
[data_test] => value
[date] => 2010-05-01 12:00:00
)
)
)
)
Try this Function. This will solve your issue.
function cleanArray($array)
{
if (is_array($array))
{
foreach ($array as $key => $sub_array)
{
$result = cleanArray($sub_array);
if ($result === false)
{
unset($array[$key]);
}
else
{
$array[$key] = $result;
}
}
}
if (empty($array))
{
return false;
}
return $array;
}
array_filter will not wrok with this array
so try this custom function
<?php
$array =array(
20 => array(
20 => array(
0=> ''
),
10 => array(
0=> 'hey'
)
)
);
function array_remove_empty($arr){
$narr = array();
while(list($key, $val) = each($arr)){
if (is_array($val)){
$val = array_remove_empty($val);
// does the result array contain anything?
if (count($val)!=0){
// yes :-)
$narr[$key] = $val;
}
}
else {
if (trim($val) != ""){
$narr[$key] = $val;
}
}
}
unset($arr);
return $narr;
}
print_r(array_remove_empty($array));
?>
found this answer here

PHP Flipping multidimentional array doesn't work

I come up with this code:
function multiArrayFlip($array)
{
$arrayCount = count($array);
if ($arrayCount != count($array, COUNT_RECURSIVE))
{
foreach($array as $key => $value)
{
if (is_array($value))
{
$array[$key] = multiArrayFlip($value);
}
}
}
else
{
array_flip($array);
}
return $array;
}
but it doesnt work.
It returns unchanged array.
here is the array data sample:
Array
(
[0] => Array
(
[0] => Array
(
[zip] => 02135
[hispanic_percent] => 7.4
[white_percent] => 73.1
[black_percent] => 4.2
[native_american_percent] => 0
)
)
[1] => Array
(
[0] => Array
(
[zip] => 02135
[school_number] => 1
[school_name] => ANOTHER COURSE TO COLLEGE
[school_address] => 20 WARREN STREET BRIGHTON MA 02135
[contact_number] => 617-635-8865
[start_grade] => 9TH GRADE
[reduced_lunch_students_count] => 8
[reduced_lunch_students_percent] => 120
[free_or_reduced_lunch_students_count] => 53
[free_or_reduced_lunch_students_percent] => 0
)
)
)
You have to reassign the return value of the array_flip function to your $array variable in order to work.
You need to modify your function to work it correctly. Reassign the values after array_flip
function multiArrayFlip($array)
{
$arrayCount = count($array);
if ($arrayCount != count($array, COUNT_RECURSIVE))
{
foreach($array as $key => $value)
{
if (is_array($value))
{
$array[$key] = multiArrayFlip($value);
}
}
}
else
{
$array = array_flip($array);
}
return $array;
}
Hope this helps :)

Categories