$array_subjected_to_search =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
),
array(
'name' => 'flash',
'type' => 'camera'
)
);
$key = array_search('flash', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);
This works fine, but is there a way to search using multiple values: eg. get key where name='flash' && type='camera' ?
is there a way to search using multiple values: eg. get key where
name='flash' && type='camera' ?
Simply with array_keys function:
$result_key = array_keys($array_subjected_to_search, [ 'type' => 'camera','name' => 'flash']);
print_r($result_key);
The output:
Array
(
[0] => 3
)
The array_search function accepts an array as parameters the following will work for the use case you provided.
$array_subjected_to_search =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
),
array(
'name' => 'flash',
'type' => 'camera'
)
);
$compare = array(
'name'=>'flash',
'type'=>'camera'
);
$key = array_search($compare, $haystack);
var_dump($haystack[$key]);
Note: your current search will not function correctly it will always return the zero index because the array_search returns 0 or false.
$key = array_search('flash', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);
I think I would just make my own function using a loop that will just retrieve the array I want based on either one or two parameters.
function getValueMatch($array, $val1, $val2 = false, $type = 'name')
{
foreach($array as $key => $row) {
# See note below, but it might be handy to have a reversible key name
if($row[$type] == $val1) {
if($val2) {
# You can put a changeable key name to reverse-find
# It might be helpful to search for the other key first
# at some point, best to keep your options open!
$altVar = ($type == 'name')? 'type' : 'name';
if($row[$altVar] == $val2)
return $row;
}
else
return $row;
}
}
}
$array =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
),
array(
'name' => 'flash',
'type' => 'camera'
)
);
print_r(getValueMatch($array,'flash','camera'));
Gives you:
Array
(
[name] => flash
[type] => camera
)
Example of reverse match (type instead of name):
print_r(getValueMatch($array,'antihero',false,'type'));
Gives you:
Array
(
[name] => snart
[type] => antihero
)
Related
I would like to replace keys in arrays, because I will move them on two indexes up.
Problem that I am facing is that those are containing same names which will not be ok, if i want to move them up.
This is how array looks like.
$list = array(
'ind' => array(
'messagetype' => 'Alert',
'visibility' => 'Public',
'info' => array(
0 => array(
'urgency' => 'Urgent',
'params' => array(
0 => array(
'Name' => 'display',
'value' => '3; top',
),
1 => array(
'Name' => 'level',
'value' => '1; blue',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GSSD154',
),
),
),
),
1 => array(
'messagetype' => 'Information',
'visibility' => 'Private',
'info' => array(
0 => array(
'urgency' => 'Minor',
'params' => array(
0 => array(
'Name' => 'display',
'value' => '1; left',
),
1 => array(
'Name' => 'level',
'value' => '1; red',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GBECS23',
),
),
),
),
),
),
),
),
);
and this is how I would like the output to be with changing keys in Name0, Name1, which are inside params.
$list = array(
'ind' => array(
'messagetype' => 'Alert',
'visibility' => 'Public',
'info' => array(
0 => array(
'urgency' => 'Urgent',
'params' => array(
0 => array(
'Name0' => 'display',
'value0' => '3; top',
),
1 => array(
'Name1' => 'level',
'value1' => '1; blue',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GSSD154',
),
),
),
),
1 => array(
'messagetype' => 'Information',
'visibility' => 'Private',
'info' => array(
0 => array(
'urgency' => 'Minor',
'params' => array(
0 => array(
'Name0' => 'display',
'value0' => '1; left',
),
1 => array(
'Name1' => 'level',
'value1' => '1; red',
),
),
'area' => array(
'ard' => 'Bob',
'code' => array(
0 => array(
'Name' => 'Badge',
'value' => 'GBECS23',
),
),
),
),
),
),
),
),
);
I have tried with a lots of examples over this website, but could not find one to achieve this.
Code that I used from
How to replace key in multidimensional array and maintain order
function replaceKey($subject, $newKey, $oldKey) {
// if the value is not an array, then you have reached the deepest
// point of the branch, so return the value
if (!is_array($subject)) {
return $subject;
}
$newArray = array(); // empty array to hold copy of subject
foreach ($subject as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$newArray[$key] = replaceKey($value, $newKey, $oldKey);
}
return $newArray;
}
$s = replaceKey($list, 'Name0', 'Name');
print "<PRE>";
print_r($s);
at the moment I get this output:
[0] => Array
(
[Name0] => display
[value] => 1; left
)
[1] => Array
(
[Name0] => level
[value] => 1; red
)
any help would be appreciated. regards
A very strange question, but why not?
The following function returns nothing (a procedure) and changes the array in-place using references but feel free to rewrite it as a "real" function (without references and with a return statement somewhere).
The idea consists to search for arrays, with numeric keys and at least 2 items, in which each item has the Name and value keys. In other words, this approach doesn't care about paths where the targets are supposed to be:
function replaceKeys(&$arr) {
foreach ($arr as &$v) {
if ( !is_array($v) )
continue;
$keys = array_keys($v);
if ( count($keys) < 2 ||
$keys !== array_flip($keys) ||
array_keys(array_merge(...$v)) !== ['Name', 'value'] ) {
replaceKeys($v);
continue;
}
foreach ($v as $k => &$item) {
$item = array_combine(["Name$k", "value$k"], $item);
}
}
}
replaceKeys($list);
print_r($list);
demo
I'm trying to write the below array if a value is set. How can I do this inside of an array? I know I could use a ternary operator but i'm not sure how.
array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
if($Value === 1){
//Need to write the below when value is true
array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
),
}
),
You cannot intersect a definition of an array with a conditional statement. What you need to do instead is to define your array first and then do an if statement which will add to the array. It's not entirely clear at what level of your array you want to add the conditional content, so I'll show it on a simplified example:
$value = 1;
$myArray = array(
'name' => 'Joe',
'kids' => array(
'name' => 'Mary',
),
);
if ($value === 1) {
$myArray['kids']['hobbies'] = 'kite flying';
}
After this, the variable $myArray will have the following content:
array(
'name' => 'Joe',
'kids' => array(
'name' => 'Mary',
'hobbies' => 'kite flying',
),
)
Where exactly you need to put your conditional data depends on the full structure of your array, but the idea is you access the parts you want through indices.
Edit: in case you can just add the needed subarray at the end of your array, you can utilize array_push.
There is 3 variants to do this:
// Variant 1
// Anonymous function, variables from the parent scope
$Value = 1;
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => function() use ($Value) {
if ($Value == 1)
return array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
);
}
);
print_r($arr['ifArray']());
// Variant 2
// Anonymous function, variable assignment
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => function($Value) {
if ($Value == 1)
return array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
),
);
}
);
$Value = 1;
print_r($arr['ifArray']($Value));
// Variant 3
// Ternar operator
$Value = 1;
$arr = array(
'name' => 'extraFields',
'attributes' => array(
'name' => 'portal',
),
'ifArray' => $Value != 1 ? null : array(
'name' => 'portal',
'value'=> '',
'attributes' => array(
'id' => '1',
'value'=> 'testportal',
)
)
);
print_r($arr['ifArray']);
However, the variant that El_Vanja suggested, might be more clear than those three.
I have two array..
Array 1
$arr1 = array(
'task' => 'delete'
)
Array 2
$arr2 = array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
How I insert Array 1 to all Array 2 collection, so the results is.
$arr2 = array(
array(
'id' => '1',
'task' => 'delete',
'type' => 'post',
),
array(
'id' => '2',
'task' => 'delete',
'type' => 'category',
),
array(
'id' => '1',
'task' => 'delete',
'type' => 'tag',
),
);
I can be easily to get the results by using looping, but I want to achieve it not using looping.
Any suggestion ?
Thank you :)
In order to push arraay1 in array2 all indexes, you can use the array_walk with a combination of array merge, you can see below code for instance
<?php
$array1 = array(
'task' => 'delete',
'before' =>'test'
);
$array2=array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
array_walk($array2, function(&$newarray) use ($array1) {
$newarray = array_merge($newarray, $array1);
});
print_r($array2);
?>
array_walk -Apply a user supplied function to every member of an array while array_merge, Merge two arrays into one array
Result
Array (
[0] => Array ( [id] => 1 [type] => post [task] => delete [before] => test )
[1] => Array ( [id] => 2 [type] => category [task] => delete [before] => test )
[2] => Array ( [id] => 1 [type] => tag [task] => delete [before] => test ) )
Git Hub
https://github.com/fahadpatel/insert-array-into-array-without-loop
DEMO
You can use array_walk to skip writing the loop.
$arr1 = array(
'task' => 'delete'
);
$arr2 = array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
array_walk($arr2, function(&$item) use ($arr1) {
$item = array_merge($item, $arr1);
});
You can see the documentation for array_walk here.
You may use array_map. It's looping behind the scenes, though (no real way around it), but at least you don't have to do it yourself:
$arr3 = array_map(static function ($entry) use ($arr1) {
return $entry + $arr1;
}, $arr2);
PHP 7.4 version:
$arr3 = array_map(static fn($entry) => $entry + $arr1, $arr2);
Demo: https://3v4l.org/2u2SR
I have an array where all arrays where key type == 'foo' must be replaced by a custom arrays.
Basically I need to find a specific array and then replace it with other arrays.
The issue here you can easily replace one array but when you insert numbers of arrays you are shifting keys so the next array type == 'foo' will not be replaced
Any help would be appreciated.
Here's what I have:
$array = array(
array(
'options' => array(
array(
'type' => 'foo'
),
array(
'type' => 'foo'
),
array(
'type' => 'bar'
)
)
),
array(
'options' => array(
array(
'type' => 'bar'
),
array(
'type' => 'bar'
),
array(
'type' => 'foo'
)
)
),
);
And I have an array which should replace any array where type == 'foo'
$array_foo = array(
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
);
Here is the desired output:
$array = array(
array(
'options' => array(
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
array(
'type' => 'bar'
)
)
),
array(
'options' => array(
array(
'type' => 'bar'
),
array(
'type' => 'bar'
),
array(
'type' => 'custom'
),
array(
'type' => 'custom_2'
),
array(
'type' => 'anything'
),
)
),
);
Thank you.
Here's a way using 2 nested foreach loops and array_merge() with a temporary array:
// Pass the array by reference
foreach ($array as &$sub) {
// Temporary array
$new_options = [];
// Loop through options
foreach ($sub['options'] as $opt) {
// if type foo: replace by $array_foo items
if ($opt['type'] == 'foo') {
$new_options = array_merge($new_options, $array_foo);
// else, keep original item
} else {
$new_options[] = $opt;
}
}
// replace the options
$sub['options'] = $new_options;
}
And check the output:
echo '<pre>' . print_r($array, true) . '</pre>';
See also Passing by Reference
According to a previous post, the code for changing could be done in a similar fashion to the following code:
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
So with your method instead of having numbers or indexes, I think you might be able to get away with writing down foo instead to get the replacement to work properly.
The other thing you might look into is array merge-recursive which can be found at: http://php.net/array_merge_recursive
The problem you stated here looks similar to this post: PHP Array Merge two Arrays on same key
I hope this helps you.
I am getting some data out of mysql into an array like this
array(
[0] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '555555'
),
[1] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '666666'
),
[2] = array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
[3] = array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
),
)
what i need to do is for each row, if the key code appears more than once, merge the rows into one but create a new array for the other_value like so
array(
[0] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => array(
[0] => '555555',
[1] => '666666'
)
),
[1] = array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
[2] = array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
),
)
What is the best way to achieve this?
I did think about looping over the each row and checking for existence of thtat key/value then do something if it exists.
#AdRock i hope you want to merge array in case of when 'code' will be same, if this is so then try below one:
<?php
$arr = array(
array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '555555'
),
array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '666666'
),
array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
)
);
echo "<pre>";
print_r($arr);// array before
$isExist = array();
foreach($arr as $key => $value){
if(in_array($value["code"], $isExist)){
$getKey = array_search($value["code"], $isExist);
$arr[$getKey]["other_value"] = array($arr[$getKey]["other_value"], $value["other_value"]);
unset($arr[$key]);
}
else{
$arr[$key] = $value;
}
$isExist[$key] = $value["code"];
}
echo "<pre>";
print_r(array_values($arr));// array after
?>
The approach that I would suggest is to loop through the array and store the value of code into a new array and store the entire result set into a new array. With each iteration, check whether the value is present or not in the code value stored array. And if value found then in that case, get the key of the code array and use the same key for the result array and store it inside the other_value. Hope it makes sense.
Looping over the array and creating a new array using the 'code' values as keys might be the simplest method. In that case you can check if the key allready exists.
$new_array=array();
foreach($array as $part){
$code_as_key = $part['code'];
//if code allready in the new array, just add a new value
if( isset($new_array[$code_as_key]) ){
$new_array[$code_as_key]['other_value'][] = $part['other_value'];
}
//else add the new code
else{
$new_array[$code_as_key]=$part;
}
}
//re-index the new array, starting from key 0
$new_array=array_values($new_array);