Filter out keys from multidimensional array - php

I have the following array:
array(2) {
[0] => array(4) {
["presentation_id"] => int(143)
["user_id"] => int(2)
["session_id"] => int(46)
["submission_id"] => int(190)
}
[1] => array(4) {
["presentation_id"] => int(144)
["user_id"] => int(2)
["session_id"] => int(46)
["submission_id"] => int(190)
}
What I want is to have an array consisting of just certain keys of this array, for example:
array(2) {
[0] => array(4) {
["presentation_id"] => int(143)
["user_id"] => int(2)
}
[1] => array(4) {
["presentation_id"] => int(144)
["user_id"] => int(2)
}
Any ideas?

$array = array_map(function ($arr) {
return array_intersect_key($arr, array_flip(array('presentation_id', 'user_id')));
}, $array);
Important to note that this syntax requires PHP 5.3+.
For other versions:
foreach ($array as &$arr) {
$arr = array_intersect_key($arr, array_flip(array('presentation_id', 'user_id')));
}
I'd suggest this over unsetting unwanted keys (as suggested by others) if you definitely want to restrict the array to certain elements. If you add more elements to the array in the future you won't need to update this code, but you'd have to unset more elements that you may not want.

Try:
$newArray = array_map(function ($innerArray) {
unset($innerArray['session_id'], $innerArray['submission_id'] /*, and so on*/);
return $innerArray;
}, $oldArray);

please use foreach and unset the key which you want to remove. Like
foreach($data as $key=> $row){
unset[$key] ["session_id"] ;
}

Related

Transform a 3-dimensional array in PHP

I have an array like this :
array(3) {
["FL_1"] => array(3) {
["MIC_1"] => array(1) {
["SP_4"] => float(7)
}
["MIC_13"] => array(1) {
["SP_16"] => float(4)
}
["MIC_6"] => array(1) {
["SP_74"] => float(4)
}
}
["FL_2"] => array(2) {
["MIC_1"] => array(1) {
["SP_5"] => float(4)
}
["MIC_13"] => array(1) {
["SP_17"] => float(4)
}
["MIC_6"] > array(1) {
["SP_75"] => float(4)
}
}
["FL_3"] => array(2) {
["MIC_1"] => array(1) {
["SP_5"] => float(89)
}
["MIC_13"] => array(1) {
["SP_18"] => float(1)
}
["MIC_6"] > array(1) {
["SP_78"] => float(21)
}
}
}
For each FL_X, I need to keep only one MIC_X that follow the conditions below :
1- This MIC_X needs to be the same for each FL_X
2- This MIC_X needs to have the lowest possible SP_Xvalue
From this example I need to get the following array
array(3) {
["FL_1"] => array(1) {
["MIC_13"] => array(1) {
["SP_16"] => float(4)
}
}
["FL_2"] => array(1) {
["MIC_13"] => array(1) {
["SP_17"] => float(6)
}
}
["FL_3"] => array(1) {
["MIC_13"] => array(1) {
["SP_18"] => float(1)
}
}
}
Any help on how to do this would be much appreciated.
Thank you !
Here's one possible solution. It uses array_walk_recursive to find the SP_X key associated with the minimum SP_X value, then it traverses the array to find the MIC_X key associated with that SP_X key and value, and finally it uses array_map and array_filter to extract only those MIC_X key values from the original array:
// find the minimum SP_X value and its key
$min_sp = PHP_INT_MAX;
$min_key = '';
array_walk_recursive($array, function ($v, $k) use (&$min_sp, &$min_key) {
if ($v < $min_sp) {
$min_sp = $v;
$min_key = $k;
}
});
// find the MIC_X key corresponding to the min SP_X value
$mic_key = '';
foreach ($array as $fl) {
foreach ($fl as $mic => $sp) {
if (isset($sp[$min_key]) && $sp[$min_key] == $min_sp) {
$mic_key = $mic;
break 2;
}
}
}
// filter the array to get all the MIC_X values
$out = array_map(function ($fl) use ($mic_key) {
return array_filter($fl, function ($mic) use ($mic_key) {
return $mic == $mic_key;
}, ARRAY_FILTER_USE_KEY);
}, $array);
print_r($out);
Output:
Array
(
[FL_1] => Array
(
[MIC_13] => Array
(
[SP_16] => 4
)
)
[FL_2] => Array
(
[MIC_13] => Array
(
[SP_17] => 4
)
)
[FL_3] => Array
(
[MIC_13] => Array
(
[SP_18] => 1
)
)
)
Demo on 3v4l.org

convert array with objects to one associative array without foreach

I have an array like(result of json_decode):
array(2) {
[0]=>
object(stdClass)#1 (3) {
["key"]=>
string(6) "sample"
["startYear"]=>
string(4) "2000"
["endYear"]=>
string(4) "2015"
}
[1]=>
object(stdClass)#2 (3) {
["key"]=>
string(13) "second_sample"
["startYear"]=>
string(4) "1986"
["endYear"]=>
string(4) "1991"
}
}
I want to convert it to array like:
array(2) {
["sample"]=>
array(2) {
["startYear"]=>
string(4) "2000"
["endYear"]=>
string(4) "2015"
}
["second_sample"]=>
array(2) {
["startYear"]=>
string(4) "1986"
["endYear"]=>
string(4) "1991"
}
}
Is there beauty way to do this (cureently I'm using foreach, but I'm not sure it is a best solution).
Added a code example:
<?php
$str='[{"key":"sample","startYear":"2000","endYear":"2015"},{"key":"second_sample","startYear":"1986","endYear":"1991"}]';
$arr=json_decode($str);
var_dump($arr);
$newArr=array();
foreach ($arr as $value){
$value=(array)$value;
$newArr[array_shift($value)]=$value;
}
var_dump($newArr);
You can use array_reduce
$myArray = array_reduce($initialArray, function ($result, $item) {
$item = (array) $item;
$key = $item['key'];
unset($item['key']);
$result[$key] = $item;
return $result;
}, array());
You can create the desired output without making any iterated function calls by using a technique called "array destructuring" (which is a functionless version of list()). Demo
Language Construct Style:
$result = [];
foreach ($array as $object) {
[
'key' => $key,
'startYear' => $result[$key]['startYear'],
'endYear' => $result[$key]['endYear']
] = (array)$object;
}
var_export($result);
Functional Style:
var_export(
array_reduce(
$array,
function($result, $object) {
[
'key' => $key,
'startYear' => $result[$key]['startYear'],
'endYear' => $result[$key]['endYear']
] = (array)$object;
return $result;
},
[]
)
);
Both will output:
array (
'sample' =>
array (
'startYear' => '2000',
'endYear' => '2015',
),
'second_sample' =>
array (
'startYear' => '1985',
'endYear' => '1991',
),
)
Simply you can use array_map like as
$result = array_map('get_object_vars',$your_array);
Edited:
As after checking your code that you've added an example over here there's no need to use an extra functions or loop to convert your array of objects into associative array instead you simply need to pass second parameter true within json_decode function like as
$arr = json_decode($json,true);
Demo
An alternative to array_reduce and other provided solutions could be:
$list = array_combine(
array_column($list, 'key'),
array_map(fn ($item) => (array) $item, array_values($list))
);
Or:
$list = array_combine(
array_column($list, 'key'),
array_map('get_object_vars', $list)
);

Search values in php array

I have an array like this:
array(5) {
[0]=> array(1) { ["go-out"]=> string(7) "#0d4b77" }
[1]=> array(1) { ["cycling"]=> string(7) "#1472b7" }
[2]=> array(1) { ["diving"]=> string(7) "#1e73be" }
[3]=> array(1) { ["exploring"]=> string(7) "#062338" }
[4]=> array(1) { ["eating"]=> string(7) "#f79e1b" }
}
Let's say I have the first value like 'cycling', so how can I find the '#147217' value?
I have been trying a lot of combinations of
foreach ( $array as $key => list($key1 ,$val)) {
if ($key1 === $id) {
return $val;
}
}
But no luck.
Ideas?
You can use array_column -
array_column($your_array, 'cycling');
DEMO
You should also add the checks for key's existence.
you may still make one loop
$id = "cycling";
foreach($array as $val)
if(isset($val[$id])) echo $val[$id];
Demo on Evail.in
I have reformated tour code, try this, that works:
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$id = "cycling";
foreach ($array as $key => $entry) {
if ($entry[$id]) {
echo $entry[$id];
}
}
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$search = "cycling";
foreach ($array as $key => $entry)
if (isset($entry[$search]))
echo $entry[$search];
That works.
Nice day.

Change indexed Array to Associative Array PHP

I have an array from json_decode. And i want to reformat it.
this is my array format.
["Schedule"]=>array(1) {
["Origin"]=>
string(3) "LAX"
["Destination"]=>
string(2) "CGK"
["DateMarket"]=>
array(2) {
["DepartDate"]=>
string(19) "2015-02-01T00:00:00"
["Journeys"]=>
array(6) {
[0]=>
array(6) {
[0]=>
string(2) "3210"
[1]=>
string(14) "Plane Name"
[2]=>
string(8) "20150201"
[3]=>
string(8) "20150201"
[4]=>
string(4) "0815"
[5]=>
string(4) "1524"
}
}
}
And i want change the indexed array to associative with foreach function.
And here is my PHP code
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value->Name= $value[1];
}
But i got an error "Attempt to assign property of non-object on line xXx..
My Question is, how to insert a new associative array to indexed array like the example that i've provide.
UPDATE : I've tried this solution
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name']=$value[1];
}
But my array format still the same, no error.
In this line:
$value->Name= $value[1];
You expect $value to be both object ($value->Name) and array ($value[1]).
Change it to something like:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$response->Schedule['DateMarket']['Journeys'][$key]['Name'] = $value[1];
}
Or even better, without foreach:
$keys = array(
0 => 'Id',
1 => 'Name',
2 => 'DateStart',
3 => 'DateEnd',
4 => 'HourStart',
5 => 'HourEnd',
);
$values = $response->Schedule['DateMarket']['Journeys'];
$response->Schedule['DateMarket']['Journeys'] = array_combine( $keys , $values );
Array_combine makes an array using keys from one input and alues from the other.
Docs: http://php.net/manual/en/function.array-combine.php
Try this:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name'] = $value[1];
}
You want to create new array index, but try to create new object.
foreach ($response->Schedule['DateMarket']['Journeys'] as $key => $value) {
$value['Name'] = $value[1];
}

Rebase array keys after unsetting elements [duplicate]

This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
Closed 2 years ago.
I have an array:
$array = array(1,2,3,4,5);
If I were to dump the contents of the array they would look like this:
array(5) {
[0] => int(1)
[1] => int(2)
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
When I loop through and unset certain keys, the index gets all jacked up.
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
unset($array[$i]);
}
}
Subsequently, if I did another dump now it would look like:
array(3) {
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
Is there a proper way to reset the array so it's elements are Zero based again ??
array(3) {
[0] => int(3)
[1] => int(4)
[2] => int(5)
}
Try this:
$array = array_values($array);
Using array_values()
Got another interesting method:
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
$array = array_merge($array);
Now the $array keys are reset.
Use array_splice rather than unset:
$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
array_splice($array, $i, 1);
}
}
print_r($array);
Working sample here.
Just an additive.
I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."
First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.
Here's my simple, working example:
$array = array(1,2,3,4,5);
for ($i = 0; $i < count($array); $i++) {
if($array[$i] == 1 || $array[$i] == 2) {
array_splice($array, $i, 1);
$i--;
}
}
Will output:
array(3) {
[0]=> int(3)
[1]=> int(4)
[2]=> int(5)
}
This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:
$files = array(
array(
'name' => 'example.zip',
'size' => '100000000',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '10726556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '110726556',
'type' => 'application/x-zip-compressed',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example2.zip',
'size' => '12356556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
'deleteUrl' => 'server/php/?file=example2.zip',
'deleteType' => 'DELETE'
)
);
for ($i = 0; $i < count($files); $i++) {
if ($i > 0) {
if (is_array($files[$i-1])) {
if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
$i--;
array_splice($files, $i, 1);
}
}
}
}
Will output:
array(1) {
[0]=> array(6) {
["name"]=> string(11) "example.zip"
["size"]=> string(9) "110726556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
}
[1]=> array(6) {
["name"]=> string(11) "example2.zip"
["size"]=> string(9) "12356556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
}
}
As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.
I use $arr = array_merge($arr); to rebase an array. Simple and straightforward.
100% working for me ! After unset elements in array you can use this for re-indexing the array
$result=array_combine(range(1, count($your_array)), array_values($your_array));
Late answer but, after PHP 5.3 could be so;
$array = array(1, 2, 3, 4, 5);
$array = array_values(array_filter($array, function($v) {
return !($v == 1 || $v == 2);
}));
print_r($array);
Or you can make your own function that passes the array by reference.
function array_unset($unsets, &$array) {
foreach ($array as $key => $value) {
foreach ($unsets as $unset) {
if ($value == $unset) {
unset($array[$key]);
break;
}
}
}
$array = array_values($array);
}
So then all you have to do is...
$unsets = array(1,2);
array_unset($unsets, $array);
... and now your $array is without the values you placed in $unsets and the keys are reset
In my situation, I needed to retain unique keys with the array values, so I just used a second array:
$arr1 = array("alpha"=>"bravo","charlie"=>"delta","echo"=>"foxtrot");
unset($arr1);
$arr2 = array();
foreach($arr1 as $key=>$value) $arr2[$key] = $value;
$arr1 = $arr2
unset($arr2);

Categories