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.
Related
This question already has answers here:
PHP array replace numbers with keys
(2 answers)
Closed 6 years ago.
When doing a print_r on my array, I get the following output;
Array
(
[0] => Array
(
[id] => 178
[name] => Briar Price
)
[1] => Array
(
[id] => 90
[name] => Bradley Kramer
)
[2] => Array
(
[id] => 508
[name] => Calvin Yang
)
[3] => Array
(
[id] => 457
[name] => Charles Valenzuela
)
... and so on
How can I modify the array to look like this;
Array
(
[178] => Briar Price
[90] => Bradley Kramer
[508] => Calvin Yang
[457] => Charles Valenzuela
... and so on
)
I just want to make the ID the key for the value name. I always have issues when it comes to arrays reordering.
Pass third parameter to array_column to make its key as
$array = array_column($users, 'name', 'id');
print_r($array);
Use foreach() -
$newArr = array();
foreach ($your_array as $key => $val) {
$newArr[$val['id']] = $val['name'];
}
print_r($newArr) // desired output
I'd use array_combine which attaches new keys to values
$results = [
['id'=>1,'name'=>'John'],['id'=>2,'name'=>'Jane'],
];
$results = array_combine(
array_column($results,'id'), //use 'id' column as keys
array_column($results,'name') //use 'name' column as values
);
//now $results is [1=>'John', 2=>'Jane']
You can do it using array_column and array_combine PHP function without applying custom logic.
Here is how you do it,
<?php
$keys=array_column($mainarray,'id');
$values=array_column($mainarray,'name');
$finalarray=array_combine($keys,$values);
$finalarray will be your desired result.
array_combine creates an array by using one array for keys and another for its values.
array_column returns the values from a single column in the input array.
My input array :
Array
(
[0] => Array
(
[id] => 1
[status_name] => Released
)
[1] => Array
(
[id] => 2
[status_name] => Under Construction
)
)
I want the output result :
Array (
[1] => Released
[2] => Under Construction
)
USe sub array id as output array key value and status_name as value array.
This is built into php as array_column. You would have:
$status_names = array_column($data, 'status_name', 'id');
print_r($status_name);
Bonus points on question as I had no idea this existed until looking for an answer for you.
Try the following:
function reOrderArray($input_array)
{
$result = array();
foreach ($input_array as $sub_array)
{
$result[$sub_array['id']] = $sub_array['status_name'];
}
return $result;
}
There might be a built-in php function to do this, array functions in php are quite powerful. I am, however, woefully unaware of one.
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
)
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.
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.