Removing nth element from an array and reindex it - php

I have an array like below
Array
(
[0] => '13-Nov'
[1] => 'PUJA SUNUWAR'
[2] => '13-Nov'
[3] => '...301303'
[4] => 'TT1331600004\DLG'
[5] => '-10000.00'
[6] => '0'
[7] => '90000.00'
)
I need to remove 4th item of array and save it as
Array
(
[0] => '13-Nov'
[1] => 'PUJA SUNUWAR'
[2] => '13-Nov'
[3] => 'TT1331600004\DLG'
[4] => '-10000.00'
[5] => '0'
[6] => '90000.00'
)
i don't want to iterate over each elements of array. Is there any one shot function like array_pop to remove nth element of array?

use array_splice($array, 3, 1);
http://php.net/manual/en/function.array-splice.php

Is this a 2d-array? If so:
No, there is no built in function to do this. You could use ´array_walk´ with a custom callback but I doubt it would be faster than a simple foreach.
Else (if normal array):
unset( $aData[3] );
$aData = array_values( $aData );
Wich is faster then array_splice.

As mentioned above, there is no build in function for that.
You should use unset if you dont need to care about array indexing and array_values if should.
Also you should use value reference while array iterating to prevent internal array copyng while values modification. If dont, it can be one of perfomance break down reasons.
foreach ($yourDataSet as &$value) {
unset($value[2]);
//$value = array_values($value);
}
You shouldt use array_splice becouse of perfomance reasons.
p.s. Also you could check phpbench for perfomance test about different types of array iteration.

Related

Nested array in php

I'm having trouble handling a nested array I get as result from an API. Print_r($result, true); returns an array looking like this (only much longer):
Array
(
[success] => 1
[return] => Array
(
[sellorders] => Array
(
[0] => Array
(
[sellprice] => 0.00000059
[quantity] => 1076.00000000
[total] => 0.00063484
)
[1] => Array
(
[sellprice] => 0.00000060
[quantity] => 927.41519000
[total] => 0.00055645
)
)
[buyorders] => Array
(
[0] => Array
(
[buyprice] => 0.00000058
[quantity] => 6535.77328102
[total] => 0.00379075
)
[1] => Array
(
[buyprice] => 0.00000057
[quantity] => 118539.39620414
[total] => 0.06756746
)
)
)
)
I need to grab the 3 values (sellprice/buyprice, quantity, total) from the first index of both arrays (sellorders and buyorders) and store them in variables ($sellprice, $sellquantity, $selltotal).
The full example php script I'm using can be found on the bottom of this page. Could anyone help me figure this out?
In php, arrays can more or less have infinite dimensions. You can go deeper within an array's dimensions by adding another set of square brackets. For example,
$array['deep']['deeper']['deepest'][0];
Assuming the indexes in the sellorders and buyorders are the same in your array, you could do
$sellprice = $result['return']['sellorders'][0]['sellprice'];
$sellquantity = $result['return']['sellorders'][0]['quantity'];
$selltotal = $result['return']['sellorders'][0]['total'];
The value should look something like this:
$sellprice = $array['return']['sellorders'][0]['sellprice']
You might want to think about how you iterate over these nested arrays in order to pick out all the values. Furthermore, if you have control over the output I might be better to use a different data structure to enable easier processing.
You can access the values of the nested arrays by adding another pair of square brackets with the appropriate index at the end:
$array['outer']['inner'];
It's up to you to transfer this knowledge to your specific array.
If you want to go thru all of those arrays... try this:
for($i=0; $i<count($array['return']['sellorders']); $i++) {
$this_array = $array['return']['sellorders'][$i];
var_dump($this_array); // it includes sellprice, quantity and total for each entity now.
}
use the same method as above for buyorders as well.

Filter and reindex array [duplicate]

This question already has answers here:
How to re-index all subarray elements of a multidimensional array?
(6 answers)
Closed 2 years ago.
I am trying to filter and reindex this array. My original array is $_SESSION['ShowingRequests'].
I've tried
array_values(array_filter($_SESSION['ShowingRequests']))
and
array_values(array_filter($_SESSION['ShowingRequests']['ListingKey']))
array_values(array_filter($_SESSION['ShowingRequests']['Key']))
but it won't reach the second level of the array.
I want it to go from this
Array
(
[ListingKey] => Array
(
[1] => 97826889139
[2] => 97820967049
[4] => 97825243774
[5] => 97824864611
)
[Key] => Array
(
[1] => 2
[2] => 3
[4] => 5
[5] => 6
)
)
to this
Array
(
[ListingKey] => Array
(
[0] => 97826889139
[1] => 97820967049
[2] => 97825243774
[3] => 97824864611
)
[Key] => Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 6
)
)
PHP arrays are not indexed, because they are not real arrays. They are in fact ordered hashmaps and as such you should not really care about the keys here. Iterating over these arrays is trivial and does not require using array_values at all.
foreach ($_SESSION['ShowingRequests']['ListingKey'] as $key => $value) {
echo "$key => $value\n";
}
Would give you...
1 => 97826889139
2 => 97820967049
4 => 97825243774
5 => 97824864611
Where you get the name of the key and the value for each element in the array using the foreach construct.
In any case you have to remember that both array_values and array_filter are non-destructive functions. They return a new array. They do not modify the array by reference. As such you must assign the return value if you want to modify the existing array. They also do not work recursively.
$_SESSION['ShowingRequests']['ListingKey'] = array_values(array_filter($_SESSION['ShowingRequests']['ListingKey']));
$_SESSION['ShowingRequests']['Key'] = array_values(array_filter($_SESSION['ShowingRequests']['Key']));
$_SESSION['ShowingRequests'] = array_values(array_filter($_SESSION['ShowingRequests']));
Is your issue to assign the filtered values back to the same key?
foreach (['ListingKey', 'Key'] as $key)
{
$_SESSION['ShowingRequests'][$key] = array_values(
array_filter($_SESSION['ShowingRequests'][$key])
);
}
Here some demonstration how it works with a helper function just to make that more visible
function array_filter_values($var) {
return array_values(array_filter($var));
}
foreach (['ListingKey', 'Key'] as $key)
{
$_SESSION['ShowingRequests'][$key] =
array_filter_values($_SESSION['ShowingRequests'][$key])
;
}
Here is an example without that helper function but with an alias of which I had thought it might make that more easy to understand but apparently not:
foreach (['ListingKey', 'Key'] as $key)
{
$var = &$_SESSION['ShowingRequests'][$key];
$var = array_values(array_filter($var));
unset($var);
}
This example code is using an alias to the variable you want to change (here the part of the array you want to change). This probably makes it more visible how it works. Because it is an alias, unset is used to remove the alias, it should not be re-used in the next iteration or after the iteration has finished.

Add array to an array with the same indexes not being merged [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Combine Two Arrays with numerical keys without overwriting the old keys
OK guys, was searching about this one with no luck - it always points only to array_merge or array_push or array_combine functions which are useless for my purpose.
Here are two arrays (number indexed):
Array (
[0] => 12345
[1] => "asdvsdfsasdfsdf"
[2] => "sdgvsdfgsdfbsdf"
)
Array (
[0] => 25485
[1] => "tyjfhgdfsasdfsdf"
[2] => "mojsbnvgsdfbsdf"
)
and I need to create one "joined" (unioned) array, so it will look like:
Array (
[0] => 12345
[1] => "asdvsdfsasdfsdf"
[2] => "sdgvsdfgsdfbsdf"
[3] => 25485
[4] => "tyjfhgdfsasdfsdf"
[5] => "mojsbnvgsdfbsdf"
)
As I found nothing on this problem I tried by myself ($arr1 and $arr2 are the two small arrays):
$result_array = $arr1;
foreach($arr2 as $v) {
$result_array[] = $v;
}
This is, of course, working fine but I don't like this approach - imagine the situation when there will not be just 3 elements in second array...
Question: is there a better approach or at the best some built-in function (I do not know about)???
array_merge will work without any problem as your using numeric keys ... see the explanation below from the docs
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
emphasis mine
Array merge works fine for your numerically indexed arrays:
<?php
$arrayOne = array(
0 => 12345
,1 => "asdvsdfsasdfsdf"
,2 => "sdgvsdfgsdfbsdf"
);
$arrayTwo = array(
0 => 25485
,1 => "tyjfhgdfsasdfsdf"
,2 => "mojsbnvgsdfbsdf"
);
$arrayMerged = array_merge($arrayOne, $arrayTwo);
print_r($arrayMerged);
?>
output:
Array
(
[0] => 12345
[1] => asdvsdfsasdfsdf
[2] => sdgvsdfgsdfbsdf
[3] => 25485
[4] => tyjfhgdfsasdfsdf
[5] => mojsbnvgsdfbsdf
)

Sort multidimensional array secondary key

I'm trying to figure out the correct function in PHP to sort a multidimensional array. I considered doing a foreach and then using ksort (this didn't work). I think it might be useful to note that the secondary keys (the numeric ones) are "manually" set (instead of using array_push since the first key in that scenario would be 0 instead of 1).
This is for a single instance so I don't need a class for this or anything super-special, I'm interested in the correct-context function in PHP to make this bit of code more performance oriented (as well as to figure out what I'm doing wrong).
Note I want to keep the PRIMARY keys (e,g, Main and Promotional) their current order.
The unsorted array...
Array
(
[Main] => Array
(
[3] => Main2
[2] => Content
[1] => Main1
)
[Promotional] => Array
(
[3] => Promotional1
[2] => Content
[1] => Promotional2
)
)
The desired outcome (sorting by second-level key)...
Array
(
[Main] => Array
(
[1] => Main1
[2] => Content
[3] => Main2
)
[Promotional] => Array
(
[1] => Promotional2
[2] => Content
[3] => Promotional1
)
)
You may try:
foreach($array as $key => $data) {
ksort($data);
$array[$key] = $data;
}
You could also try this:
foreach($array as $key => &$data) {
ksort($data);
}
the ampersand before the $data variable indicates that the $data variable is a pointer, and any changes to that variable will cascade back to the original configuration.

Removing a value from a PHP Array

Using PHP I'm trying to remove an element from an array based on the value of the element.
For example with the following array:
Array
(
[671] => Array
(
[0] => 1
[1] => 100
[2] => 1000
)
[900] => Array
(
[0] => 15
[1] => 88
}
)
I'd like to be able to specify a value of on of the inner arrays to remove. For example if I specified 100 the resulting array would look like:
Array
(
[671] => Array
(
[0] => 1
[2] => 1000
)
[900] => Array
(
[0] => 15
[1] => 88
}
)
My first thought was to loop through the array using foreach and unset the "offending" value when I found it, but that doesn't seem to reference the original array, just the loop variables that were created.
Thanks.
foreach($array as $id => $data){
foreach($data as $index => $offending_val){
if($offending_val === 100){
unset($array[$id][$index]);
}
}
}
You can use:
array_walk($your_array, function(&$sub, $key, $remove_value) {
$sub = array_diff($sub, array($remove_value));
}, 100);
Couple of ideas:
You could try array_filter, passing in a callback function that returns false if the value is the one you want to unset. Using your example above:
$new_inner_array = array_filter($inner_array, $callback_that_returns_false_if_value_100)
If you want to do something more elaborate, you could explore the ArrayIterator class of the SPL, specifically the offsetUnset() method.

Categories