I'm trying to manipulate an associative multidimensional array. I've extracted the keys from an array that I want to apply to another's values . . .
These are the keys that I've extracted in another function
$keys = array (
"id" => "id",
"addr_street_num" => "addr_street_num",
"addr_street" => "addr_street",
"price" => "price",
"days" =>"days",
"state" => Array
(
"id" => "id",
"name" => "name"
),
"city" => Array
(
"id" => "id",
"web_id" => "web_id",
"name" => "name"
)
);
This array has the values I'd like to combine together
$vals = array (
"0" => "830680",
"1" => "20",
"2" => "Sullivan Avenue",
"3" => "333000",
"4" => "12",
"5" => Array
(
"0" => "4",
"1" => "Maryland",
),
"6" => Array
(
"0" => "782",
"1" => "baltimore",
"2" => "Baltimore",
)
);
When I try to do array_combine($keys, $val);
I get 2 Notices about Array to string conversion
I guess array_combine only works on one dimensional arrays, any ideas on how to approach this?
If $keys was modified could it be combined with the values - problem is the shape of $keys is what I want to end up with?
It can be done recursively.
function combine_recursive($keys, $values) {
$result = array();
$key = reset($keys);
$value = reset($values);
do {
if (is_array($value)) {
$result[key($keys)] = combine_recursive($key, $value);
} else {
$result[key($keys)] = $value;
}
$value = next($values);
} while ($key = next($keys));
return $result;
}
This works for me with your example arrays. I'm sure this will give you all kinds of weird results/errors if the array structures are different from each other at all.
Related
This question already has answers here:
Remove unwanted elements from subarrays in multidimensional array
(3 answers)
Closed 6 months ago.
I have a multi dimensional array like below.
array:1 [
0 => array:3 [
"picture_id" => "0"
"car_name" => "CA"
"from" => "2020"
"to" => "2020"
]
]
I need to remove from & to from the above array and return result in same structure.
I have tried following code
$whitelist = array("from", "to");
$finalArray = [];
foreach ($records as $record) {
foreach ($record as $key => $item) {
if (!in_array($key, $whitelist)) {
$finalArray[$key] = $item;
}
}
}
But the result I am getting is not multi-dimensional array like this:
array:1 [
"picture_id" => "0"
"car_name" => "CA"
]
My expected result is:
array:1 [
0 => array:3 [
"picture_id" => "0"
"car_name" => "CA"
]
]
You can try something like this:
$array = [
[
"picture_id" => "0",
"car_name" => "CA",
"from" => "2018",
"to" => "2020"
],
[
"picture_id" => "1",
"car_name" => "WA",
"from" => "2010",
"to" => "2019"
]
];
$whitelist = array("from", "to");
$finalArray = [];
foreach ($array as $k => $record) {
foreach ($record as $key => $item) {
if (!in_array($key, $whitelist)) {
$finalArray[$k][$key] = $item;
}
}
}
print("<pre>".print_r($finalArray,true)."</pre>");
What will print out:
Array
(
[0] => Array
(
[picture_id] => 0
[car_name] => CA
)
[1] => Array
(
[picture_id] => 1
[car_name] => WA
)
)
A short explanation...Basically you are looping over multi dimensional array as
foreach($array as $key => $value)
Where value is "inner" array, so in order to remove some elements from inner, and create a new multi dimensionalarray, you have to use keys, like in my example, from original array. So you than actually make an array like:
$newArray[$key] = $innerArray
And this gives you multi dimensional array.
BR
Rather than having to go through each field to determine if it should be removed, you can use array_diff_key() to remove all of the columns in one go. This needs you to create a list of the fields you want to remove and for each record just get the difference between the record and the keys to remove...
// Keys to remove (note as key rather than value)
$remove = ["from" => 1, "to" => 1];
$finalArray = [];
foreach ($array as $record) {
$finalArray[] = array_diff_key($record, $remove);
}
print_r($finalArray);
Try This
$result = [];
foreach($yourArray as $key => $value){
unset($value['from']);
unset($value['to']); //You can unset as many columns as you want specifically.
$result[] = $value;
}
print_r($result);
I have array inside array:
{
"0" => array("key" => "code", "id" => "4", "value" => "yes"),
"1" => array("key" => "parameter", "id" => "4", "value" => "0"),
"2" => array("key" => "code", "id" => "5", "value" => "no"),
etc...
}
This is what I want to do: I want to have one dimension array in which key would be "id" and value would be "value". However, I need to filter out entries whose key is "parameters". So, in this example, the final array should look like this:
{
"4" => "yes",
"5" => "no"
}
I just can't seem to figure out how to do this. Could you please help me a bit? I tried writing this foreach inside foreach but I just can't wrap my head around how to filter data.
foreach ($settings AS $key => $value) {
$id = null;
$value = null;
foreach ($value AS $key2 => $value2) {
// No idea how to filter out uneccesary entries and save the correct ones
}
$finalArray[$id] = $value;
}
This should do it :
$finalArray = array();
foreach ($settings as $setting) {
if ($setting['key'] != 'parameter') {
$finalArray[$setting['id']] = $setting['value'];
}
}
Assuming all your entries have keys 'key', 'id' and 'value'.
use array_column and array_filter like this, if you want to filter more keys add them to out_keys array :
<?php
$array = [
["key" => "code", "id" => "4", "value" => "yes"],
["key" => "parameter", "id" => "4", "value" => "0"],
["key" => "code", "id" => "5", "value" => "no"]
];
$out_keys = ['parameter'];
$result = array_column(array_filter($array, function($item) use($out_keys) {
return !in_array($item['key'], $out_keys);
}), 'value', 'id');
echo "<pre>";
print_r($result);
output:
Array
(
[4] => yes
[5] => no
)
Assuming $data is your starting array, the code below will output what you want in $result
$result = [];
foreach(array_filter($data, function($el){return $el['key']!='parameter';}) as $el){
$result[$el['id']] = $el['value'];
}
Live demo
My problem is so twisted that I don't even know how to start to explain it.
Lets say that I have several assosiative arrays (not always the same arrays: sometimes I have the products array, sometimes I have the markets array, sometimes I have the segment array, etc...). $values is the only array I always get!
$values = array ("0" => "1", "4" => "2", "5" => "3");
$products = array ("0" => "1", "1" => "1", "2" => "2", "3" => "1", "4" => "2", "5" => "3");
$markets = array ("0" => "1", "3" => "1", "4" => "2", "5" => "3");
...
I want to build an array with the values of each of the arrays I get, with the values matching the keys.
Something like
$myArray = array ("0" => array ( "values" => "1", "products" => "1", "markets" => "1"),
"1" => array ( "products" => "1"),
"2" => array ( "products" => "2"),
"3" => array ( "products" => "1", "markets" => "1"),
"4" => array ( "values" => "2", "products" => "2", "markets" => 2),
...);
I've tried something like this:
switch ($_POST["cpv_type"]) {
case "pClass":
$keyValue = $_POST["cpv_type"];
$objKey = "this->productClasses";
break;
case "pMarket":
$keyValue = $_POST["cpv_type"];
$objKey = "this->markets";
break;
case "pSegment":
$keyValue = $_POST["cpv_type"];
$objKey = "this->productSegments";
break;
case "pType":
$keyValue = $_POST["cpv_type"];
$objKey = "this->productTypes";
break;
default:
$keyValue = "products";
$objKey = "this->products";
break;
}
And then I do a foreach cicle:
// all values must be floats
if(!empty($this->value)){
foreach ($this->value as $key => &$curVal){
// if no value has been entered, exclude it and also associated product from validation
if (strlen(trim($curVal)) == 0) {
unset($this->value[$key]);
unset($this->products[$key]);
} else {
// This validates my variable
$curVal = TMS::checkVar($curVal, "dec", $_SESSION["dico"]->_VALUE_, 100, false);
// Store the value on existing array, associating "hoppValue" to the right key entry!
$logDetail[$keyValue][${$objKey}[$key]]["hoppValue"] = $curVal;
}
}
}
My problem is in the variable variable:
How do I access, for example $this->productTypes[5] using variable variable syntax?
I get "null" for all var_dumps of $$objKey, ${$objKey}, ${$objKey}[$key], ${$objKey[$key]}, $$objKey[$key]
Thank you for your help!
you can simple get array in case $objKey = $this->productClasses and used as $objKey[$key]. And you can replace $objKey to $arrayClasses or similary for good understending code.
p.s. sorry for my English.
For example a multidimensional array like an example below
$arr = array(
[H1] => array(
"name" => "A"
"title" => "T1"
)
[H2] => array(
"name" => "B"
"title" => "B1"
)
)
Let's say I would like to search name which equals to A in $arr and if it's matched, the searching should return the key which is H1
How can I do that in php ?
I tried array_keys($arr, "A") but it returns me with an array instead of the key.
This may help -
$arr = array(
'H1' => array(
"name" => "A",
"title" => "T1",
),
'H2' => array(
"name" => "B",
"title" => "B1",
)
);
// Generate a new array with 'keys' and values in 'name'
$new = array_combine(array_keys($arr), array_column($arr, 'name'));
// Search in that new array
$search = array_search('A', $new);
var_dump($search);
Output
string(2) "H1"
Demo
Another simple way would be -
$serach= false;
foreach($arr as $key => $val) {
if($val['name'] == 'A') {
$search= $key;
break;
}
}
var_dump($search);
I have the following array:
$array = Array(
"0" => Array (
"id" => 1081,
"name" => "John"
),
"1" => Array (
"id" => 1082,
"name" => "Matt"
),
"2" => Array (
"id" => 1083,
"name" => "Roger"
)
);
Is there anyway I can get name if I only know the id but without having to iterate through the array?
For PHP >= 5.5.0:
$id = 1082;
$result = array_column($array, 'name', 'id')[$id];
As Barmar points out, to get an array that is easy to use with id as the index:
$id = 1082;
$result = array_column($array, 'name', 'id');
echo $result[$id];
You can make an associative array that refers to the same elements, then use that:
function make_assoc(&$array, $keyname) {
$new_array = array();
foreach ($array as &$elt) {
$new_array[$elt[$keyname]] = $elt;
}
return $new_array;
}
$assoc_array = make_assoc($array, 'id');
Now you can use $assoc_array[1083] to access the third item in the original array. And since this returns an array of references, modifying that will also modify the element of the original array.
You can use array_map to search into your array if your PHP < 5.5.0 and you don't have array_column:
<?php
$array = Array(
"0" => Array (
"id" => 1081,
"name" => "John"
),
"1" => Array (
"id" => 1082,
"name" => "Matt"
),
"2" => Array (
"id" => 1083,
"name" => "Roger"
)
);
$find = 1082;
$value = '';
$arr = array_map(function($n) use ($find, &$value) {if ($n['id'] == $find) $value = $n['name']; }, $array);
print_r($value);
?>