cannot find value in array - php

I can't see where I am wrong with this code so I kindly ask for your help.
I have two arrays:
Array (
[0] => Array (
[description] => Generali di Proprieta'
[idmov] => 34
[mov] => Manutenzioni
[total] => 8000
)
[1] => Array (
[description] => Generali di Proprieta'
[idmov] => 35
[mov] => Assicurazioni
[total] => 6000
)
[2] => Array (
[description] => Generali di Proprieta'
[idmov] => 36
[mov] => Cancelleria Postali
[total] => 1850
)
[3] => Array (
[description] => Generali di Proprieta'
[idmov] => 37
[mov] => Bancarie passive
[total] => 700
)
[4] => Array (
[description] => Generali di Proprieta'
[idmov] => 38
[mov] => Amministrazione
[total] => 15000
)
)
and
Array (
[0] => Array (
[center] => 8
[caus] => 34
[total] => 38175.04
)
[1] => Array (
[center] => 8
[caus] => 35
[total] => 6132.00
)
[2] => Array (
[center] => 8
[caus] => 36
[total] => 223.80
)
[3] => Array (
[center] => 8
[caus] => 37
[total] => 114.70
)
[4] => Array (
[center] => 8
[caus] => 38
[total] => 14625.07
)
[5] => Array (
[center] => 8
[caus] => 39
[total] => 7450.48
)
I use this function
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['caus'] === $id) {
return $key;
}
}
return null;
}
to look in array B for each item of array A with this code:
for($i=0;$i<$length;$i++){
if(searchForId($voce_bdg[$i]['idmov'], $voce_actual)){
$key=searchForId($voce_bdg[$i]['idmov'], $voce_actual);
$actual=$voce_actual[$key]['importo'];
echo '<td class="report">'.number_format($actual,2,',','.').'</td>';
}else{
echo '<td class="report">0,00</td>';
}
}
It works for every item like a charm except for the first item where it returns 0.
Where am I wrong??
Thanks in advance for your help!
Lelio

PHP treats the index 0 as a false. As such, if you find your result in index zero, it won't pass the if() statement you have.
Since your function returns null if no record found, why not try to check for null?
for($i = 0; $i < $length; $i++)
{
// Use is_null() check below. If it is not null, it is found.
// Also, instead of doing searchForId() twice, just do it once and check for the result.
$key = searchForId($voce_bdg[$i]['idmov'], $voce_actual);
if(! is_null ($key))
{
$actual = $voce_actual[$key]['importo'];
echo '<td class="report">'.number_format($actual,2,',','.').'</td>';
}
else
{
echo '<td class="report">0,00</td>';
}
}

try replacing operator === for ==

It does return something. It return 0 since the key is 0. But your if() interpret it as a "false"
change
if(searchForId($voce_bdg[$i]['idmov'], $voce_actual)){
with
if(searchForId($voce_bdg[$i]['idmov'], $voce_actual) != null){

Related

Remove duplicates array

I have an array looks like this,
Array
(
[0] => Array
(
[id] => 224983
[name] => James
[weight] => 0
[bank] => Bank A
[transaction] => 1
[total] => 7682000000
[reference] => Edward
[type] => BRANCH
[reference_id] => 222818
[account_number] => 1220007355285
)
[1] => Array
(
[id] => 224984
[name] => James
[weight] => 0
[bank] => Bank A
[transaction] => 1
[total] => 7682000000
[reference] => Edward
[type] => BRANCH
[reference_id] => 222819
[account_number] => 1220007355285
)
[3] => Array
(
[id] => 224985
[name] => Maria
[weight] => 0
[bank] => Bank B
[transaction] => 1
[total] => 1500000000
[reference] => Andrey
[type] => BRANCH
[reference_id] => 247620
[account_number] => 1220000412901
)
)
When the account_number, reference, and name is same I want to remove the other one, and keep the last based on id...
Please someone help me to find out, I've been stuck here, so the output would be remove array[0] with ['id] => 224983, and the rest array would be the result
If you specifically just want to compare only three field of array than you can try below way. Which checks of duplicate and unset previous entries. Here $data is array input
foreach ($data as $key => $row) {
$id = $row['id'];
$name = $row['name'];
$reference = $row['reference'];
$flag = 0;
for($i = $key + 1; $i < count($data); $i++)
{
if(($data[$i]['id'] == $id) && ($data[$i]['name'] == $name) && ($data[$i]['reference'] == $reference))
{
if($key != $i)
unset($data[$key]);
}
}
}
Result would be
Array
(
[1] => Array
(
[id] => 224983
[name] => James
[weight] => 0
[bank] => Bank A
[transaction] => 1
[total] => 7682000000
[reference] => Edward
[type] => BRANCH
[reference_id] => 222818
[account_number] => 1220007355285
)
[2] => Array
(
[id] => 224985
[name] => Maria
[weight] => 0
[bank] => Bank B
[transaction] => 1
[total] => 1500000000
[reference] => Andrey
[type] => BRANCH
[reference_id] => 247620
[account_number] => 1220000412901
)
)
Try the following function, This will help to remove duplicates arrays.
function array_unique_multidimensional($input)
{
$serialized = array_map('serialize', $input);
$unique = array_unique($serialized);
return array_intersect_key($input, $unique);
}
It seems inelegant, but I think you would need to loop through your previous array elements to check IDs. You could create a function something like this:
function id_exists_prior(&$my_array, $array_index) {
for($i = 0; $i < $array_index; $i++) {
if($my_array[$i]['id'] === $my_array[$array_index]['id']) return false;
}
return true;
}
Then you can call it on any array element you wish, or loop through the whole array to check for duplicates. An example of the latter:
$your_array = [/*Your array data*/];
for($key = 0; $key < count($your_array); $key++) {
if(id_exists_prior($your_array, $key)) //Do your thing
}
The reason for passing the array key into the function is so that the function ONLY checks for prior duplicates.
Hope this helps!

How to check for a value in a multi dimensional array

My Array is below
$sample_arr = Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 20
[ref] => ref 2
)
[2] => Array
(
[index] => 2
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 21
[ref] => ref 2
)
)
As you can see in the above array there is article_Id twice in the array with value 6
I would like to find the details of the second row so that I can make the second row qty 41 i.e my result array will be like the one below
I have tried the in_array function but still there is something missing
I also tried with the foreach but the problem is that how to get the first appearance row qty? i.e in the $sample_arr when the user adds the third record with article_Id 6 the second row must be updated as shown below
$result_arr = Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref goes here
)
)
Looks like article ID is unique. So, we can kep storing data in this $newArray variable with the key as article ID.
Every time, it's checked if a record containing the article id exists. If so, the quantity is added. If not, it's appended to the $newArray.
$newArray = array();
foreach($sample_arr as $arr) {
if (isset($newArray[$arr['article_Id']])) {
$newArray[$arr['article_Id']]['qty'] += $arr['qty'];
$newArray[$arr['article_Id']]['ref'] = 'Ref goes here'; // If this the string that replaces the ref
} else {
$newArray[$arr['article_Id']] = $arr;
}
}
$newArray = array_values($newArray);
Output:
Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
Try the following:
$new_merged_array = array();
if(!empty($sample_arr )){
foreach($sample_arr as $sample_ar){
if(!empty($sample_ar) && isset($sample_ar['article_Id'])){
if(isset($new_merged_array[$sample_ar['article_Id']])){
$new_merged_array[$sample_ar['article_Id']]['qty'] += $sample_ar['qty'];
}else{
$new_merged_array[$sample_ar['article_Id']] = $sample_ar;
}
}
}
}
print_r($new_merged_array);
Output will be:
Array(
[4] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[6] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
Another way:
$new_merged_array = $sample_array = array();
if(!empty($sample_arr )){
foreach($sample_arr as $sample_ar){
if(!empty($sample_ar) && isset($sample_ar['article_Id'])){
if(isset($new_merged_array[$sample_ar['article_Id']])){
$new_merged_array[$sample_ar['article_Id']]['qty'] += $sample_ar['qty'];
}else{
$new_merged_array[$sample_ar['article_Id']] = $sample_ar;
}
}
}
}
if(!empty($new_merged_array )){
foreach($new_merged_array as $new_merged_arr){
$sample_array[] = $new_merged_arr;
}
}
print_r($sample_array);
Output will be:
Array(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
$sample_arr = array
(
0 => array
(
'index'=> 0,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 4,
'qty' => 50,
'ref' => 'ref'
),
1 => array
(
'index' => 1,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 6,
'qty' => 20,
'ref' => 'ref 2'
),
2 => array
(
'index' => 2,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 6,
'qty' => 21,
'ref' => 'ref 2'
)
);
$articleArray = [];
foreach($sample_arr as $key=>$value){
$articleId = $value['article_Id'];
if(array_key_exists($articleId,$articleArray)){
$articleArray[$articleId]['qty'] = $articleArray[$articleId]['qty'] + $value['qty'];
}else{
$articleArray[$articleId] = $value;
}
}
$articleArray = array_values($articleArray);
print_r($sample_arr);
print_r($articleArray);
Demo
in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Usage:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';

fetch value from a given array

I have an array stored in $result like this
$result=$array
by using echo $result i get the following array
Array
(
[success] => 1
[product] => Array
(
[id] => 83
[seo_h1] =>
[name] => Beer Week
[manufacturer] => The Boxer Store
[model] => WPEB/0413/74/BW
[sku] => WPEB/0413/74/BW
[reward] => 0
[points] => 0
[image] => asd
[images] => Array
(
[0] => asd
)
[quantity] => 4
[price] => Rs.599
[special] =>
[discounts] => Array
(
)
[options] => Array
(
[0] => Array
(
[product_option_id] => 42
[option_id] => 25
[name] => Size Option
[type] => select
[option_value] => Array
(
[0] => Array
(
[product_option_value_id] => 165
[option_value_id] => 72
[name] => Large
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
[1] => Array
(
[product_option_value_id] => 166
[option_value_id] => 73
[name] => XL
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
[2] => Array
(
[product_option_value_id] => 163
[option_value_id] => 70
[name] => Small
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
[3] => Array
(
[product_option_value_id] => 164
[option_value_id] => 71
[name] => Medium
[option_sku] =>
[image] => asd
[price] =>
[price_prefix] => +
)
)
[required] => 1
)
)
[minimum] => 1
[rating] => 0
[description] => as
[attribute_groups] => Array
(
)
[date_added] => 2014-09-30 12:35:12
[date_modified] => 2014-10-17 17:33:46
[currency] => INR
[status] => 1
)
)
i am able to fetch the result individually like this
$finalid = $array['product']['id'];
echo $finalid;
but wish to fetch each and every data even the inner most values using for loop. for this i tried this
$c=count($result);
for ( $i=0; $i < $c; $i++)
{
echo $array[$i]['id'];
echo $array[$i]['images'][0];
echo $array[$i]['options'][0]['product_option_id'];
echo $array[$i]['images'][0]['option_value'][0]['product_option_value_id'];
echo $array[$i]['images'][0]['option_value'][1]['product_option_value_id'];
}
but it didn't displayed any result can anyone tell how it can be done
Use:
$products = $result['product'];
foreach ( $products as $product )
{
echo $product['id'];
echo $product['images'][0];
echo $product['options'][0]['product_option_id'];
echo $product['images'][0]['option_value'][0]['product_option_value_id'];
echo $product['images'][0]['option_value'][1]['product_option_value_id'];
}
You may want a recursive function like this to print your multidimensional arrays:
function printIt($data){
if (is_array($data)){
foreach ($data as $index=>$slice){
if (is_array($slice)){
printIt($slice);
}else{
echo $index.": ".$slice."<br>";
}
}
}else{
echo $data."<br>";
}
}
printIt($yourArray);
Use foreach instead,
foreach ( $array['product'] as $product)
{
echo $product['id'];
echo $product['images'][0];
echo $product['options'][0]['product_option_id'];
echo $product['options'][0]['option_value'][0]['product_option_value_id'];
echo $product['options'][0]['option_value'][1]['product_option_value_id'];
}
Here you will be looping inside each element of $array['product'] and for each loop $product will have the current element of $array['product'].
The mistake in your attempt was in [$i]. For each loop $i would have 0,1,2 etc and the array index would be $array['product'][0],etc but there is no element of that sort. Your method works if your array is an Indexed array, but here it is an Associative Array.
Try this,
<?php
foreach($result as $res){
echo '<pre>'; echo $res['id'];
if(is_array($res['options']) && !empty($res['options'])) {
foreach($res['options'] as $option) {
echo '<pre>'; echo ($option['product_option_id']);
if(is_array($option['option_value']) && !empty($option['option_value'])) {
foreach($option['option_value'] as $option_value) {
echo '<pre>'; echo $option_value['product_option_value_id'];
}
}
}
}
?>

Find key based on value PHP

[items] => Array
(
[0] => Array
(
[product_option_id] => 328
[option_id] => 26
[name] => Product Type
[type] => checkbox
[group_no] => 1
[option_value] => Array
(
[0] => Array
(
[product_option_value_id] => 1473
[option_value_id] => 68
[option_boolean_value] => True
[option_cost] => 10.0000
[option_enable] => 1
[apply_default] => 1
[apply_option] => 0
)
[1] => Array
(
[product_option_value_id] => 1474
[option_value_id] => 151
[option_boolean_value] => False
[option_cost] => 0.0000
[option_enable] => 1
[apply_default] => 0
[apply_option] => 0
)
)
[required] => 1
[optionapply] => A
[booleanvalue] => True
[applyheading] => 1
[flagheading] => 0
[dhead_id] => 0
[routes_dephead_id] => Array
(
[0] => 44
[1] => 37
)
[routes_id] => Array
(
[0] => 948
[1] => 949
)
)
How can i get the key where option_value_id is 68. Here 68 is not static each time it will be dynamic i want dynamic solution.
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
http://php.net/manual/en/function.array-search.php
Try This one.
function search_id($array, $id)
foreach ($array['items'] as $key => $val) {
foreach($val['option_value'] as $option_key => $option_value)
{
if ($option_value['option_value_id'] == $id)
{
return $option_key;
}
}
}

PHP search array in array

I have array result like this:
Array
(
[0] => stdClass Object
(
[id_global_info] => 78
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:54
[date_expires] => 2012-04-14 16:11:54
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[1] => stdClass Object
(
[id_global_info] => 79
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[2] => stdClass Object
(
[id_global_info] => 80
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
.
.
.
)
How can I search a multidimensional array and count number of results (for example I want to search for info_type_id with value of 4)?
Use array_filter to filter the array:
function test($arr) {
return $arr["info_type_id"] == 4;
}
echo count(array_filter($yourArray, "test"));
with foreach ?
function searchMyCoolArray($arrays, $key, $search) {
$count = 0;
foreach($arrays as $object) {
if(is_object($object)) {
$object = get_object_vars($object);
}
if(array_key_exists($key, $object) && $object[$key] == $search) $count++;
}
return $count;
}
echo searchMyCoolArray($input, 'info_type_id', 4);
You should try this :
$counter = 0;
$yourArray; // this var is your current array
foreach($yourArray as $object){
if($object->info_type_id == 4){
$counter++;
}
}

Categories