I have an array of 50000 arrays and i want to remove the "id" key-value pair from each of them.
I would rather not loop through 50k elements and was wondering if there was an efficient way to do it.
Array
(
[0] => Array
(
[id] => 713061
[market] => usd-btc
[price] => 3893.69
)
[1] => Array
(
[id] => 713056
[market] => usd-btc
[price] => 3893.69
)
[2] => Array
(
[id] => 713051
[market] => usd-btc
[price] => 3893.69
)
[3] => Array
(
[id] => 713046
[market] => usd-btc
[price] => 3893.69
)
[4] => Array
(
[id] => 713041
[market] => usd-btc
[price] => 3892.95
)
[5] => Array
(
[id] => 713036
[market] => usd-btc
[price] => 3892.95
)
I tried both the following but does not seem to be working:
// Remove ID
foreach($server_data as $sd)
{
unset($sd['id']);
}
unset($server_data['id']);
PRINT_R($server_data);
The $server_data is still returning the array with the $id element;
Any thoughts?
This creates a copy of the subarray, so when you change it, the main array is not affected:
foreach ($server_data as $sd)
{
unset($sd['id']);
}
You can unset from the original array:
foreach (array_keys($server_data) as $index)
{
unset($server_data[$index]['id']);
}
Or pass the subarray a reference so that the original is changed:
foreach ($server_data as &$sd)
{
unset($sd['id']);
}
Or, more tersely:
array_walk($server_data, function (&$item) { unset($item['id']); });
There's no reason I can think of to remove it (just ignore it), however you can run it through a callback that removes id and returns the rest:
$server_data = array_map(function($v) { unset($v['id']); return $v; }, $server_data);
Related
I want to remove parent array index in array.
Following is my array.
Array
(
[0] => Array
(
[0] => Array
(
[id] => 296
[username] => David0123
[profile_slug] => david-love
)
)
[1] => Array
(
[0] => Array
(
[id] => 297
[username] => Anne_wils
[profile_slug] => anne-chase
)
)
[2] => Array
(
[0] => Array
(
[id] => 300
[username] => malina001
[profile_slug] => malina-reid
)
)
)
And I want like this way..
Array(
[0] => Array
(
[id] => 296
[username] => David0123
[profile_slug] => david-love
)
[1] => Array
(
[id] => 297
[username] => Anne_wils
[profile_slug] => anne-chase
)
[2] => Array
(
[id] => 300
[username] => malina001
[profile_slug] => malina-reid
)
)
I used following script for it but not work.
$myMainArray = json_decode(json_encode($allEscorts),true);
$i=0;
foreach( array_values($myMainArray) as $k=> $val){
echo $val[$i]['id'];
$i++;
}
I want to display data each element but first i have to remove parent array indexes.
You can use array_map to pull values up one level
$myMainArray = json_decode(json_encode($allEscorts),true);
$myMainArray = array_map(function($el) {
return $el[0];
}, $myMainArray);
You should check if the first array could be generate as you wish.
If not you can use array_map to get the first index from the inner-array.
for example:
$result = array_map(function($item){
return $item[0]; // always return the first array-index
}, $first_array);
Help me pls combine array values.
I have the same array:
In my case i should save customers name like a key.
Array
(
[Test Name] => Array
(
[0] => Array
(
[name] =>
banana
[id] =>
45002
[quantity] =>
10
)
[1] => Array
(
[name] =>
banana
[id] =>
45002
[quantity] =>
20
)
[3] => Array
(
[name] =>
apple
[id] =>
23402
[qua] =>
1
)
[5] => Array
(
[name] =>
cherry
[id] =>
40017
[qua] =>
7
)
How to get something like this:
Array
(
[Test Name] => Array
(
[0] => Array
(
[name] =>
banana
[id] =>
45002
[quantity] =>
30 // summ quantity but unique name and id
)
[1] => Array
(
[name] =>
apple
[id] =>
23402
[qua] =>
1
)
[2] => Array
(
[name] =>
cherry
[id] =>
40017
[qua] =>
7
)
In my case i should save customers name like a key.
Then i will upload this on a table.
You can use array_map and array_reduce to accomplish it:
$results = array_map(function ($result) {
return array_reduce($result, function ($carry, $item) {
if (isset($carry[$item['id']])) {
$carry[$item['id']]['quantity'] += $item['quantity'];
} else {
$carry[$item['id']] = $item;
}
return $carry;
}, array());
}, $results);
From the documentation:
array_map() returns an array containing all the elements of array1 after applying the callback function to each one.
array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value.
In our case the callback given to the array_reduce function returns a final array which contains unique items by id.
I'm trying to unset two specific array positions which contain two values.
My actual code to fill the array.
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
return $storeArray;
}
$store = get_store_list();
The array looks like the following incase ill echo it out using print_r function:
Array
(
[0] => Array
(
[name] => Artizans
[id] => 20037336
)
[1] => Array
(
[name] => Bwabies!
[id] => 20080134
)
[2] => Array
(
[name] => Crave Mart
[id] => 20097365
)
[3] => Array
(
[name] => David & Goliath
[id] => 20099998
)
[4] => Array
(
[name] => Domo
[id] => 20098166
)
[5] => Array
(
[name] => Emily the Strange
[id] => 20101926
)
[6] => Array
(
[name] => Garfield
[id] => 20098167
)
[7] => Array
(
[name] => Jetsetter
[id] => 26
)
[8] => Array
(
[name] => Like Dat
[id] => 3
)
[9] => Array
(
[name] => Paris Hilton
[id] => 21
)
[10] => Array
(
[name] => Peppermint Place
[id] => 12
)
[11] => Array
(
[name] => Rocawear
[id] => 19
)
[12] => Array
(
[name] => ShoeBuy
[id] => 10
)
[13] => Array
(
[name] => Skelanimals
[id] => 20100198
)
[14] => Array
(
[name] => Snoop Dogg
[id] => 20
)
[15] => Array
(
[name] => SW&TH
[id] => 20096121
)
[16] => Array
(
[name] => The Castle
[id] => 1
)
[17] => Array
(
[name] => The Lair
[id] => 4
)
[18] => Array
(
[name] => The Mix
[id] => 923
)
[19] => Array
(
[name] => The Powerpuff Girls
[id] => 20098121
)
[20] => Array
(
[name] => The Surf Shop
[id] => 5
)
[21] => Array
(
[name] => Tie The Knot
[id] => 20076231
)
[22] => Array
(
[name] => tokidoki
[id] => 20099224
)
[23] => Array
(
[name] => University Club
[id] => 2
)
[24] => Array
(
[name] => Z Avenue
[id] => 6
)
[25] => Array
(
[name] => Z's Greetings
[id] => 20099506
)
)
Now $store does contain 2 array indexes which I have to delete. Which are the following ids: 21 and 20076231
I've been trying the following already:
Array search code without beeing success. Does anyone have a idea what I could try?
There are a handful different approaches for this simple issue. One of them could be using function array_filter():
/**
* #param array $list the list to process
* #param array $IDsToRemove the IDs of elements to remove from $list
* #return array a subset of $list that does not contain elements having 'id' in $IDsToRemove
*/
function removeFromArray(array $list, array $IDsToRemove)
{
return array_filter(
// Filter the input list...
$list,
// ... using a function...
function (array $item) use ($IDsToRemove) {
// ... that accepts an element if its "id" is not in $IDsToRemove
return ! in_array($item['id'], $IDsToRemove);
}
);
}
// Usage
$filteredStore = removeFromArray($store, array(21, 20076231));
Try this in your loop, this will not include in your array than no need to unset like this:
foreach($data as $store) {
if($store['id'] == '20076231')
continue;
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
If you need to unset an item from your array after it's been created, take a look at array_map.
First map your array to retrieve the index of each ID.
$map = array_map(function($item){ return $item['id']; }, $store);
Then get the index of your ID from the map (e.g. 21).
$index = array_search(21, $map);
Then remove with array_splice.
array_splice($store, $index, 1);
why not use directly the id in your $storeArray? And as it seems to be integer why do you force it to (string)?
Try this:
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[(int)$store['id']] = array(
"name" => (string)$store['name']
);
}
return $storeArray;
}
// delete the keys you want
unset ($storeArray[21], $storeArray[20076231]);
// or if you have more ids to delete you can create a deleteArray
$deleteArray = array(2, 20076231);
foreach ($deleteArray as $toDelete){
unset($storeArray($toDelete);
}
One line code is cool but sometimes explicit code is preferable.
function filter_by_id(array $data, $id)
{
foreach ($data as $k => &$v) {
foreach ((array) $id as $i) {
if ($v['id'] === $i) {
$v = null;
}
}
}
// 'array_filter()' produces a new array without the null entries.
// 'array_values()' produces a new array with indexes without gaps.
return array_values(array_filter($data));
}
You can filter by one id at time
$store = filter_by_id($store, 21);
Or you can filter multiple ids at the same time:
$store = filter_by_id($store, [21, 20076231]);
I want to merge the 2 arrays of objects based on the 'id' field of Array1 and the 'itemVendorCode' of Array2. I also wanted to remove from the resulting arrays of object anything that didn't match.
Array1:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 89-575-2354
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 230.35
)
)
Array2:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I was able to solve this by this code:
$indexed = array();
foreach($itemsArray as $value) {
$indexed[$value->itemVendorCode] = $value;
}
$results = array();
foreach($vendorItems as $obj) {
$value = $indexed[$obj->id];
if (isset($value)) {
foreach($value as $name => $val) {
$obj->$name = $val;
array_push($results, $obj);
}
}
}
print_r($results);
credits to the original poster. I just modified it a bit,
I was able to get the result like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[1] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[2] => stdClass Object
(
[id] => 14-102-1010
[qty] => 16
[price] => 3.2
[internalId] => 57033
[itemVendorCode] => 14-102-1010
)
)
I think you will have to use array_map function which provides you a callback function to execute on array(s).
In the callback function:
- declare your array1
- foreach the second array
- set an if statement to check that the current iteration with the id value matches the itemVendorCode of the array2 and return it
something like this:
// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
// you foreach this array
foreach ($array2 as $obj2) {
// if the value of id matches itemVendorCode
if ($obj1->id === $obj2->itemVendorCode) {
// you return the id
return $obj->id;
}
}
};
// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);
This code is a sample but doesn't provide you, your needled solution, try to update it to do what you exactly want ;)
What is a function I can use that's basically the opposite of doing
if(strpos($array['some_key'], $value)!==false) {
that means there's a match and confinue
}
I basically want to loop through two arrays and grab the ones that don't have a match to the $value in $array.
$array =
Array
(
[0] => GPPZ20
[1] => GPPZ45
[2] => GPPZ75
[3] => GPPZH20
[4] => GPPZH45
)
$codes =
Array
(
[0] => Array
(
[count] => 1
[code] => GPPZH20SWYE4A2VZU
[amount] => 20
)
)
Array
(
[0] => Array
(
[count] => 1
[code] => GPPZH2077434178J6
[amount] => 20
)
)
Array
(
[0] => Array
(
[count] => 17
[code] => PMMC4
[amount] => 25
)
)
Array
(
[0] => Array
(
[count] => 1
[code] => GPPZH2052910M8V62
[amount] => 20
)
)
Array
(
[0] => Array
(
[count] => 1
[code] => GPPZH45B3116LD1VW
[amount] => 45
)
)
so what i want to do is grab all the ones in the $codes array where the $codes['code'] value does not match any of the ones in the $array value.
right now i have the ones that match and grabbing those by doing
foreach($codes as $code) {
foreach($array as $key=>$value) {
if(strpos($code['code'], $value)!==false) {
//it matches grab those values
}
}
}
I basically now need something like this to grab the ones that do not match
You should use array_filter function - http://php.net/manual/en/function.array-filter.php e.g.:
function myFilter($val){ return strpos('foo', $val) === false; }
$array = array("foobar", "foo", "bar");
var_dump(array_filter($array, myFilter));
You can also use preg_match method instead of strpos.