Most Efficient Way to Delete Nested Array Element - php

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.

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;});

merging array in CI 3

I want to merge two arrays in order to get the data as per my requirement.
I am posting my result, please have a look.
First array:
Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
)
)
Second array:
Array
(
[0] => Array
(
[user_id] => 9c2e00508cb28eeb1023ef774b122e86
[car_id] => 14783
[status] => favourite
)
)
I want to merge the second array into the first one, where the value at key car_id matches the equivalent value; otherwise it will return that field as null.
Required output:
<pre>Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
[fav_status] => favourite
)
)
Since the merge is so specific I would try something like this:
foreach ($array1 as $index => $a1):
foreach ($array2 as $a2):
if ($a1['car_id'] == $a2['car_id']):
if ($a2['status'] == "favourite"):
$array1[$index]['fav_status'] = "favourite";
endif;
endif;
endforeach;
endforeach;
You might be able to optimize the code more but this should be very easy to follow...
Another way to achieve this without using the index syntax is to reference the array elements in the foreach by-reference by prepending the ampersand operator:
foreach($firstArray as &$nestedArray1) {
foreach($secondArray as $nestedArray2) {
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1['fav_status'] = $nestedArray2['status'];
}
}
}
You can see it in action in this Playground example.
Technically you asked about merging the arrays. While the keys would be different between the input arrays and the desired output (i.e. "status" vs "fav_status"), array_merge() can be used to merge the arrays.
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 = array_merge($nestedArray1, $nestedArray2);
}
Playground example.
Additionally the union operators (i.e. +, +=) can be used.
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator1
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 += nestedArray1;
}
Playground example.
1http://php.net/manual/en/function.array-merge.php#example-5587

checking condition in multi dimensional array

I want to check a multi dimensional array for a key value and print its parent array's another key value. This might confuse a bit. But the below example can make it clear. I have a array like this.
Entity Response : Array
(
[0] => Array
(
[type] => FieldTerminology
[relevance] => 0.709023
[count] => 4
[text] => domain name
)
[1] => Array
(
[type] => Company
[relevance] => 0.603375
[count] => 2
[text] => Laravel
)
[2] => Array
(
[type] => Person
[relevance] => 0.548389
[count] => 1
[text] => M. Naveen Kumar
)
I want to check if any array has a key [type] and its value = "Person" , then i want to get its value of the key[text]. In this case I want to print M. Naveen Kumar
You can traverse the array to find it. you can use foreach(), array_walk() and so on.
$o = [];
array_walk($array, function($v) useļ¼ˆ&$o){$v['type'] == 'Person' ? $o[] = $v['text'] : '';});
var_dump($o);
Try this
$people = array_filter($array, function($each) { return $each['type'] == 'Person'; });
$names = array_map(function($each) { return $each['name']; }, $people);
How does this work step by step?
Filter the array by type using array_filter
Then map to names using array_map

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.

php array merge with value of parent array

I need to merge an array with value of parent array.
$testArr=unserialize('a:6:{s:5:"queue";a:2:{i:6;s:1:"5";i:5;s:1:"2";}s:3:"sum";a:2:{i:6;s:3:"765";i:5;s:3:"2.1";}s:7:"sumAccD";a:2:{i:6;s:3:"543";i:5;s:3:"3.1";}s:7:"sumAccC";a:2:{i:6;s:2:"54";i:5;s:3:"3.3";}s:7:"comment";a:2:{i:6;s:12:"test comment";i:5;s:6:"111222";}s:3:"yt0";s:0:"";}');
$ret = array();
foreach ($testArr as $pkey => $pval) {
if (is_array($pval)) {
foreach ($pval as $pvkey => $pvval) {
$ret[$pvkey] = array($pkey => $pvval);
}
}
}
echo '<pre>', print_r($ret), '</pre>';
In this case it prints out
Array
(
[6] => Array
(
[comment] => test comment
)
[5] => Array
(
[comment] => 111222
)
)
1
Unfortunally it print out only comment. I need to add other rows: queue,sum,sumAccD,sumAccC. Array must look like this:
Array
(
[6] => Array
(
[queue] => 5
[sum] => ''
....
[comment] => test comment
)
[5] => Array
(
[queue] => 2
[sum] => 2.1
....
[comment] => 111222
)
)
1
Please help merge them.
Thanks.
Look at this line:
$ret[$pvkey] = array($pkey => $pvval);
You're assigning the key to a new array every time, overwriting what was previously there.
In your case, 'comment' is the last key that is processed, so that's going to be the only key in the final array.
Instead of this, you could define a new array only once outside the inner for, like this:
$ret[$pvkey] = array();
And then assign your values to that array in the inner for loop as you would normally do (so no more creating arrays there!)
Problem solved by replacing
$ret[$pvkey] = array($pkey => $pvval);
with
$ret[$pvkey][$pkey] = $pvval;

Categories