Unable to access nested array in php - php

I have an array like them i would like to access this sub category array like this
foreach($data as $parent_category){
$ndata=$parent_category['subCategory'];
foreach ($ndata as $subCategory){
}
}
Where $data is my main array print_r($data) give this output
When i access this array i got an error Undefined index: subCategory
Help me please ...
Array (
[1] => Array
(
[name] => Indian Culture
[subCategory] => Array
(
[0] => Array
(
[name] => Indain Culture-1
[articleId] => 10
)
[1] => Array
(
[name] => culture -1
[articleId] => 22
)
)
)
[5] => Array
(
[name] => ABC CULTURE
)
)

As You see, here:
[5] => Array
(
[name] => ABC CULTURE
)
Your array does not contain element with index "subCategory". So just check, that the index is present by invoking:
...
if (isset($parent_category['subCategory'])) {
...

Array key 5 doesn't have a subCategory index.
The first entry in the array will be fine.
You can check if subCategory is present using the array_key_exists function.
http://uk1.php.net/array_key_exists
Difference between isset and array_key_exists

Item with key 5 does not contain subCategory key. To avoid warnings, try with:
foreach($data as $parent_category){
if (isset($parent_category['subCategory'])) {
$ndata = $parent_category['subCategory'];
foreach ($ndata as $subCategory){
}
}
}

Modified your code as below, so you will not get undefined index for those cases where you didn't have subcategory.
foreach($data as $parent_category){
$ndata=isset($parent_category['subCategory'])?$parent_category['subCategory']:'';
if(!empty($ndata)){
foreach ($ndata as $subCategory){
}
}
}

Related

Deleting complex array element

So I want to delete an array element from a JSON array based on an id in a sub-array. I know it sounds weird. Here's an example of the array. I want to delete the entire array [0] based on the [dealer][id] array where the [id] = 20220 in this example.
Array
(
[results] => Array
(
[offset] => 1
[length] => 15
[data] => Array
(
[0] => Array
(
[dealer] => Array
(
[id] => 20220
[name] => apple
)
)
)
)
}
In reality there are a lot more elements in the [results] array. I'm not sure how to go about it.
Any help is greatly appreciated!
Loop thru data key first then check if dealer id matches the searched id
$id = 20220;
foreach ($array['results']['data'] as $key => $value) {
if ($value['dealer']['id'] == $id) {
unset($array['results']['data'][$key]);
}
}
use array_filter,
$array['results']['data'] = array_filter($array['results']['data'], function($v){return $v['dealer']['id'] != 20220;});

Convert multiple-dimensional array in to one dimensional array by summing the vaues like shown here

Array
(
[0] => Array
(
[0] => 17
[1] => 111
)
[1] => Array
(
[0] => 17
[1] => 10
)
[2] => Array
(
[0] => 20
[1] => 111
)
)
I want to convert this array as:
array
(
[17]=>121
[20]=>111
)
is there any php array function which can do it easily. I know the other way, but want to know if any ready made function can do that or not??
Please Help.
Here I actually wanted to convert
[0] => Array
(
[0] => 17
[1] => 111
)
17 to key and take 111 as value then in next array
[1] => Array
(
[0] => 17
[1] => 10
)
do the same thing get first value 17 as key and add 10 into previous value 111
which is 121 and then
[2] => Array
(
[0] => 20
[1] => 111
)
take 20 as key and assign value 111 to that key so basically, I want first value as a key and second value as value and for all same keys I want to add values as I stated before.
I thought there might be any PHP ready-made function for that as I have seen there are lots of array processing functions available in PHP. Now, I realized there is no any such kind of function available. I can do my own custom code for this purpose but was looking for good logical solution.
No builtin function for that but it is a simple foreach loop. Assume your array is stored in variable $arr;
$return = array();
foreach ($arr as $a) {
$return[$a[0]] += $a[1];
}
echo "<pre>"; print_r($return);
if you are calling multiple times then you can easily write your own function
$arr[0]= array(17,111);
$arr[1]= array(17,10);
$arr[2]= array(20,111);
$return = subArr($arr);
echo "<pre>"; print_r($return);
function subArr($arr) {
$result = array();
foreach ($arr as $a) {
$result[$a[0]] += $a[1];
}
return $result;
}

How to set new index in previous array using for each loop

here is my code
array 1:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
)
)
array 2:
Array
(
[0] => Array
(
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
[company_id] => 42166
)
)
php code:
$total = count($result);
$i=0;
foreach ($result as $key=>$value) {
$i++;
$company_id= implode(",",(array)$value['id']);
if ($i != $total)
echo',';
}
code to fetch array 2:
foreach ($res as $key1=>$value1) {
echo $total;
$event[$value['company_name']] = $value1['Product_Name'];
if($value1['company_id']==$company_id )
{
echo " match";
//$key[['company_name']]= $value1['Product_Name'];
}
else
{
echo "not matched";
}
}
what i need create a new index if company_id is match with id of another array.
that is product_name.
if product name is there just create index otherwise show null.
i want show in key=> value .
output should be like:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
)
)
Your all problems with keys in arrays will disappear when you will start using company ids as a keys.
To reindex you arrays, you can use:
$array1 = array_combine(array_column($array1, 'id'), $array1);
$array2 = array_combine(array_column($array2, 'company_id'), $array2);
In the output you will get:
array 1:
Array
(
[42166] => Array
(
[id] => 42166
...
)
)
And array 2 will looks similiar - id as a key.
So accessing to the elements using ids as a keys is a piece of cake right now.

Most Efficient Way to Delete Nested Array Element

Say I have the following:
Array(
[0] => Array
(
[id] => 1
[item] => first item
)
[1] => Array
(
[id] => 3
[item] => second item
)
[2] => Array
(
[id] => 5
[item] => third item
)
)
I want to delete the item with id = 5. I know I can loop through the array and unset, but I'm hoping for a more direct/efficient solution.
If you cannot make the IDs the keys of the outer array (then you could simply use unset($arr[5]);), looping over the array is indeed the way to dg.
foreach($arr as $key => $value) {
if($value['id'] === 5) {
unset($arr[$key]);
break;
}
}
Another option would be using array_filter - that's less efficient though since it creates a new array:
$arr = array_filter($arr, function($value) {
return $value['id'] !== 5;
});
Why don't you create the array with the keys set as the ID's? E.g:
Array(
[1] => Array
(
[id] => 1
[item] => first item
)
[3] => Array
(
[id] => 3
[item] => second item
)
[5] => Array
(
[id] => 5
[item] => third item
)
)
You can then write:
<?php
unset($array[5]); // Delete ID5
?>
For Multi level nested array
<?php
function remove_array_by_key($key,$nestedArray){
foreach($nestedArray as $k=>$v){
if(is_array($v)){
remove_array_by_key($key,$v);
} elseif($k==$key){
unset($nesterArray[$k]);
}
}
return $nestedArrat;
}
?>
The most efficient way would be to have 2 arrays.
ID => Index
Index => Object (your current array)
Search for ID in your ID => Index helper array and the value will be the Index for your main array, then unset them both.

Check Arrays with different keys?

How do i check if a specific array key exist and how to compare them?
1. Array looks like this.
[33] => Array
(
[211] =>objectr
(
[name] => Test
[id]=> 211
)
)
[23] => Array
(
[311] =>objectr
(
[name] => Tester
[id]=> 311
)
)
2. Array looks like this
[0] => 311
[1] => 211
[2] => 99
Now i need to compare them and get the id of them.
What im looking for is something like that
[0] => Tester
[1] => Test
How do i do that?
array_key_exists - http://php.net/manual/en/function.array-key-exists.php
foreach($first_array as $arr) {
foreach($second_array as $key=>$val)
{
if (array_key_exists($val, $first_array)) {
$final_array[$key] = $arr['name'];
}
}
}
or array_search - http://uk.php.net/array_search
foreach($first_array as $arr) {
foreach($second_array as $val)
{
$key = array_search($val, $arr);
if($key !== false) $final_array[$key] = $arr['name'];
}
}
In both cases you should end up with:
[0] => Tester
[1] => Test
I would transform Array 1 like removing the outer key (at least temporarily) then while iterating through Array 2, i'd compare against transformed Array 1 with array_key_exists.
I hope I understood your question, there might be a language barrier, but here we go:
so basically you have 3 arrays and you want to use the last to to check against the first one to see if those values/keys exists in the first? Well the firs thing you want to do is re structure your first array into something that can easily be translated for checking the values and keys of the next two arrays. so lets call the first array $mapArray:
foreach($mapArray as $mapObject){
foreach($mapObject as $object){
$mapList[$object->id] = $object->name;
}
}
Now this should give us something like:
[211] => 'test'
[311] => 'tester'
So now lets call the 2nd array $arrayIds and the 3rd $arrayNames. To see if am id exists and to get its name when given the array $arrayIds, all you need to do is this:
//given [0] => 311
$keyExists = array_key_exists(311, $mapList); //returns true is the key exists
echo $mapList[311]; //returns tester, the name for the id given
And the other way around:
//given [0] => 'test'
$nameExists = in_array('test', $mapList);
if($nameExists) echo array_search('test', $mapList); // returns 211
hope this is what you are looking for or at least helps you find what you are looking for.
Another approach: We reduce the first array to one dimension:
$first = array();
foreach($first_array as $val) {
$first[key($val)] = current($val);
}
gives:
Array
(
[211] => Array
(
[name] => Test
[id] => 211
)
[311] => Array
(
[name] => Tester
[id] => 311
)
)
(I used an array instead of an object but it works the same).
and then we compute the intersection of the keys:
//assume
$second_array = array(311, 99);
$result = array_intersect_key($first, array_flip($second_array));
which gives:
Array
(
[311] => Array
(
[name] => Tester
[id] => 311
)
)
So it is not quite what you want but you can easily access the name property via $element->name.

Categories