Find value and key in multidimensional array - php

I have the following array:
Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
I need to find if [position] => 22 exists in my array and retain the array path for further reference. Thank you.

Example of code for the solution "Ancide" provide.
$found = false;
foreach ($array as $array_item) {
if (isset($array_item['position'] && $array_item['position'] == "22")) {
$found = true;
break;
}
}

You can try this code:
$array = array
(
array (
"word" => 1,
"question" => php,
"position" => 11
),
array (
"word" => sql,
"question" => 1,
"position" => 22
)
);
foreach($array as $item)
{
foreach($item as $key=>$value)
{
if($key=="position" && $value=="22")
{
echo "found";
}
}
}

First check if they key exists using isset, then if the key exists, check that the value is equal to your compare value.
Edit: I missed that there were two arrays. To solve this, iterate through each array and do the check in each cycle. If the check is positive you know which array it is by looking at the current index.

I think there is no other solution than to loop through the array an check whether there is a key "position" and value "22"

This will solve your problem:
<?php
foreach ($array as $k => $v) {
if(isset($v['position']) && $v['position'] == 22) {
$key = $k;
}
}
echo $key;
//$array[$key]['position'] = 22
?>

Try this:
function exists($array,$fkey,$fval)
{
foreach($array as $items)
{
foreach($items as $key => $val)
if($key == $fkey and $val == $fval)return true;
}
return false;
}
Example:
if(exists($your_array,"position",22))echo("found");

function findPath($array, $value) {
foreach($array as $key => $subArray) if(subArray['position'] === $value) return $key;
return false; // or whatever if not found
}
echo findPath($x, 22); // returns 1
$x= Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)

Try with this function:
function findKey($array, $mykey) {
if(array_key_exists($mykey, $array))
return true;
foreach($array as $key => $value) {
if(is_array($value))
return findKey($value, $mykey);
}
return false;
}
if(findKey($search_array, 'theKey')) {
echo "The element is in the array";
} else {
echo "Not in array";
}

Related

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

How can i return all the results from my array?

Array
(
[edit] => true
[id] => 1
[type] => Array
(
[0] => LC
)
[userid] => 1
[norooms] => 1
[park] => Central
[start] => 09:00
[end] => 11:00
[length] => 2
[student] => 79
[status] => Rejected
)
<?php
$posted_data = array();
if (!empty($_POST['edit'])) {
$posted_data = json_decode($_POST['editVal'], true);
}
print_r ($posted_data);
foreach ($posted_data as $key => $value) {
echo '<p>'.$key.'</p>';
echo '<p>'.$value.'</p>';
}
?>
The array at the top is the jason_decode returned. However with my foreach function it does not display the first index of the array within the array. ie. ( [0] => LC ).
Where am I going wrong?
You need to build a recursive function, something like:
function print_recursively(array $array)
{
foreach ($array as $key => $value)
{
if(is_array($value))
{
print_recursively($value);
}
else
{
echo '<p>'.$key.'</p>';
echo '<p>'.$value.'</p>';
}
}
}
Tune it according to your needs.
If you know there is array hierarchy to one level only
Keep printing the values and if the value is an array using is_array.. Iterate again.
foreach($dataArray as $key =>$value){
if(is_array($value)){
foreach($value as $array2Data){
echo $array2Data; //you can use keys as well
}
}
else
echo $value;
}

Remove element from multidimensional indexed array by value using PHP

I have array:
Array
(
[5] => Array
(
[0] => 19
[1] => 18
)
[6] => Array
(
[0] => 28
)
)
And I'm trying to delete element by value using my function:
function removeElementWithValue($obj, $delete_value){
if (!empty($obj->field)) {
foreach($obj->field as $key =>$value){
if (!empty($value)) {
foreach($value as $k=>$v){
if($v == $delete_value){
$obj->field[$key][$k] = '';
}
}
}
}
}
return urldecode(http_build_query($obj->field));
}
echo removeElementWithValue($request, '19');
After operation above I have: 5[0]=&5[1]=18&6[0]=28; // Right!!!
echo removeElementWithValue($request, '18');
After operation above I have: 5[0]=&5[1]=&6[0]=28; // Wrong ???
But my expected result after second operation is:
5[0]=19&5[1]=&6[0]=28;
Where is my mistake?
Thanks!
Use array_walk_recursive to find and change value
$arr = Array (
5 => Array ( 0 => 19, 1 => 18 ),
6 => Array ( 0 => 28));
$value = 18;
array_walk_recursive($arr,
function (&$item, $key, $v) { if ($item == $v) $item = ''; }, $value);
print_r($arr);
result:
Array (
5 => Array ( 0 => 19, 1 => ),
6 => Array ( 0 => 28));
A simpler function might be..
function removeElementWithValue($ar,$val){
foreach($ar as $k=>$array){
//update the original value with a new array
$new_ar = array_diff_key($array,array_flip(array_keys($array,$val)));
if($new_ar){
$ar[$k]=$new_ar;
}else{
unset($ar[$k]);//or remove the empty value
}
}
return $ar;
}

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 :)

count of duplicate elements in an array in php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/
The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}
$array = array('192', '202', '192', '202');
print_r(array_count_values($array));
$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}
Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;
Check with in_array() function.

Categories