The output of the below makes $new_array contain multiple arrays with an id, date and type.
$new_array = array();
foreach($things as $thing )(
$new_array[] = array(
'id' => $thing['id'],
'date' => '2017-01-01',
'type' => $thing['type']
);
)
If I print_r( $new_array ) this gets me all the arrays inside, but then I want to modify this array and remove all the arrays inside which don't have a specific type.
To do this I assume I need to unset any $new_array[] arrays where the key value pair type => equals x.
How do I acheive this? I have read into unsetting key value pairs but this doesn't help me with it being multiple arrays.
Perhaps you should check first before adding the array:
foreach($things as $thing ){
if(!empty($thing['type']) && $thing['type'] == 'my type'){
$data[] = [
'id' => $thing['id'],
'date' => '2017-01-01',
'type' => $thing['type']
];
}
}
print_r($data);
Related
I have an array with an index. The index is not static and keeps changing.
$fields = [
11 => array (
'fieldId' => 'ORStreet',
'type' => 'TEXT',
'value' => 'Postbus 52',
),
];
Index of the above one is 11. But sometimes it becomes a different number.
One thing that always stays the same is the fieldId. How can i get the index of this array by only knowing the field id.
This above array is a child of the main array called 'fields'.
In my head i have something like this:
Loop through the main array called fields > if you find an array with fieliD => ORStreet. Return the index of that array.
If its not possible to get an index this way, i wouldnt mind if I got the 'value' => 'Postbus52' key-pair.
<?php
$arr = [
[
'fieldId' => 'ORStreet',
'type' => 'TEXT',
'value' => 'Postbus 52',
],
[
'fieldId' => 'vbnm',
'type' => 'TEXT',
'value' => 'Postbus 52',
],
[
'fieldId' => 'ORStreet',
'type' => 'TEXT',
'value' => 'Postbus 52',
]
];
shuffle($arr);
foreach ($arr as $key => $value) {
if(array_key_exists("fieldId", $value) && $value["fieldId"] === "ORStreet"){
echo $key;
break;
}
}
?>
I have used shuffle method to simulate randomness of the array. Then I have loop through the array to match fieldId with specified value(ORStreet) . If it got match then the loop will terminates and display the index.
Another Way:
$filteredArr = array_pop(array_filter($arr, function ($a){
return array_key_exists("fieldId", $a) && $a["fieldId"] === "ORStreet";
}));
You can use combination of array_map() and array_flip()
$index = array_flip(array_map(function($val){
return $val["fieldId"];
}, $arr));
echo $index["ORStreet"];
// output: 11
Check result in demo
One more possibility:
$result = array_keys(
array_combine(array_keys($fields), array_column($fields, "fieldId")),
"ORStreet"
);
array_column() extracts all the fieldId values, and then array_keys() searches for your desired value, returning the relevant array keys.
Note this will return an array of keys. If you only want the first key, this will return it as an integer:
$result = array_search(
"ORStreet",
array_combine(array_keys($fields), array_column($fields, "fieldId"))
);
I am trying to find the difference of 2 multidimensional arrays. I am attempting to solve this with a modified recursive array difference function.
If I have the following array setup:
$array1 = array(
0 => array(
'Age' => '1004',
'Name' => 'Jack'
),
1 => array (
'Age' => '1005',
'Name' => 'John'
)
);
$array2 = array(
0 => array(
'Age_In_Days' => '1004',
'Name' => 'Jack'
),
1=> array(
'Transaction_Reference' => '1005',
'Name' => 'Jack'
)
);
I am trying to match the arrays however the keys are not the same. I want to return the difference between the two multidimensional arrays where
$array1[$i]['Age'] == $array2[$i]['Age_In_Days'];
I want to keep the original array structure if the above condition holds true so the output I am looking for is:
$diff = array (1 => array (
'Age' => '1005',
'Name' => 'John'
));
However I am having issues with how to modify the recursive function to achieve this. Any help is appreciated! Thanks!
You need to loop through first array and compare values with second array. Then follows your condition. If condition is true then push this unique value to third array. Values in third array are now diff between first and second array.
$diff = [];
foreach ($array1 as $value1) {
foreach ($array2 as $value2) {
if ($value1['Age'] !== $value2['Age_In_Days']) {
array_push($diff, $value1);
}
}
}
I have a multi array e.g
$a = array(
'key' => array(
'sub_key' => 'val'
),
'dif_key' => array(
'key' => array(
'sub_key' => 'val'
)
)
);
The real array I have is quite large and the keys are all at different positions.
I've started to write a bunch of nested foreach and if/isset but it's not quite working and feels a bit 'wrong'. I'm fairly familiar with PHP but a bit stuck with this one.
Is there a built in function or a best practise way that I can access all values based on the key name regardless of where it is.
E.g get all values from 'sub_key' regardless of position in array.
EDIT: I see now the problem is that my "sub_key" is an array and therefore not included in the results as per the first comment here http://php.net/manual/en/function.array-walk-recursive.php
Just try with array_walk_recursive:
$output = [];
array_walk_recursive($input, function ($value, $key) use (&$output) {
if ($key === 'sub_key') {
$output[] = $value;
}
});
Output:
array (size=2)
0 => string 'val' (length=3)
1 => string 'val' (length=3)
You can do something like
$a = [
'key' => [
'sub_key' => 'val'
],
'dif_key' => [
'key' => [
'sub_key' => 'val'
]
]
];
$values = [];
array_walk_recursive($a, function($v, $k, $u) use (&$values){
if($k == "sub_key") {
$values[] = $v;
}
}, $values );
print_r($values);
How does it work?
array_walk_recursive() walks by every element of an array resursivly and you can apply user defined function. I created an anonymous function and pass an empty array via reference. In this anonymous function I check if element key is correct and if so it adds element to array. After function is applied to every element you will have values of each key that is equal to "sub_key"
I have below multidimensional array and I want to replace value of
$data['meta']['attr']['road'] with an array ['test']
Thing is I don't know keys they are only available through keys array
$keys = ['meta', 'attr', 'road'];
This is just an example keys might be anything hence want to search each element, check it and replace if key is found
My multidimensional array is below:
$data = ['meta' => [
'time' => 11.364,
'count' => 3,
'attr' => [
'id'=> 7845,
'road' => [
'length' => 'km',
'width' => 'm'
]
]
],
'Assets' => [15,78,89]
];
Looks complicated search and replace algorithm really stuck ...any thoughts?
$keys = ['meta', 'attr', 'road'];
$arr = &$data;
foreach($keys as $key)
{
$arr = &$arr[$key];
}
$arr = ['test'];
You can access multidimensional array values using brackets and keys.
// set
$someArray['key']['key'] = 'value';
// get
$someVar = $someArray['key']['key'];
See arrays section on Php reference
So in your case it is;
$data['meta']['attr']['road'] = array('test' => 'value');
I have two arrays:
$array = [
'application' => [
'foo' => [
'bar' => 1
]
]
];
$array_2 = [
0 => 'application',
1 => 'foo',
2 => 'bar'
];
How can I change the value of the first array knowning that the last key in the second array is the key who's value must be changed in the first array?
As you can see the second array contains all the keys from the first array. I want to do something like:
$array[$array_2] = 2;
... I suppose I must create a for loop?
For example, if I want to change the bar key value, I must do:
$array['application']['foo']['bar'] = 2;
... but I don't know which key I must change, I only have an array containing keys, and the last key in the list is the key that's value must be changed.
You could build a recursive function, or use a reference:
$result =& $array;
foreach($array_2 as $key) {
$result =& $result[$key];
}
$result = 2;
print_r($array);
This will do it, although not sure what you are trying to achieve.
$array[$array_2[0]][$array_2[1]][$array_2[2]] = 2;
Recursively add the keys. This works -
function get_keys($arr, &$keys){
$keys = array_merge($keys,array_keys($arr));
foreach($arr as $a){
if(is_array($a)){
get_keys($a, $keys);
}
}
}
$array = Array(
'application' => Array(
'foo' => Array(
'bar' => 1
)
)
);
$keys = Array();
get_keys($array, $keys);
var_dump($keys);
OUTPUT-
array
0 => string 'application' (length=11)
1 => string 'foo' (length=3)
2 => string 'bar' (length=3)