I have an associative array
array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
)
What i Want to do is catch all the array keys where the key name has similarities
for example
i want to echo out item_name (it should get both item_name1 & item_name2) but i require it in a loop (foreach/for) so that i can send within the loop the details to my database for each set of values
Thanks For the help
Use the funtion array_keys
$allKeys = array_keys($yourArray);
$amountKeys = count($allKeys);
Unless you do not provide more code this will give you all the keys of $yourArray
Reference - array_keys
To get all the similar keys you can use this function similar-text()
Since I do not know how "similar" a key can be I would suggest you to test out different values and find a degree that matches your expectations.
Your data model seems to use numeric suffixes as a replacement for arrays so I'll assume that key name has similarities is an overestimated problem statement and you merely want to fix that.
The obvious tool is regular expressions:
$original_data = array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
);
$redacted_data = array();
foreach ($original_data as $key => $row) {
if (preg_match('/^(.+)(\d+)$/u', $key, $matches)) {
$redacted_data[$matches[1]][$matches[2]] = $row;
} else {
$redacted_data[$key][] = $row;
}
}
var_dump($redacted_data);
It should be easy to tweak for your exact needs.
I can't figure out what the i require it in a loop (foreach/for) requirement means but you can loop the resulting array as any other array:
foreach ($redacted_data as $k => $v) {
foreach ($v as $kk => $vv) {
printf("(%s,%s) = %s\n", $k, $kk, $vv);
}
}
<?php
$items=[];
$itemsNumbers=[];
foreach($itemarr as $key=> $val)
{
$itempos = strpos("item_name", $key);
if ($pos !== false)
$items[]=$val;
$numberpos = strpos("item_number", $key);
if ($numberpos !== false)
$itemsNumbers[]=$val;
}
?>
Note: here $itemarr is your input array
$items you will get list of item names and $itemsNumbers you will get list of itemsNumbers
Related
Say you have the array .
$arr = array('foo' => 'bar, 'wang' => 'chung', 'ying' => 'yang');
Now I want to loop through another array (var = $terms) to get values using foreach. If the value is any of the keys listed in $arr, I want to replace it with the value listed in $arr.
I've tried this ...
foreach($terms as $term => $arr) {
echo $term[$arr];
}
This doesn't work ... and I'm pretty stumped beyond that point. Reading through the manual on foreach ... I felt like this was on the right path - but think I'm needing a nudge in another direction.
Thoughts?
You can use array_key_exists() function for verifying whether key exists in another array or not If found then replace that with existing once. You can refer below answer,
$arr = array('foo' => 'bar', 'wang' => 'chung', 'ying' => 'yang');
$res = [];
foreach($terms as $term => $arr1) {
if( array_key_exists( $term, $arr ) ) {
$res[$term] = $arr[$term];
} else {
$res[$term] = $arr1;
}
}
echo '<pre>'; print_r($res);
I hope this will resolve your problem.
I have an array like this:
array(
'firstName' => 'Joe',
'lastName' => 'Smith'
)
I need to loop over every element in my array and in the end, the array should look like this:
array(
'FirstName' => 'Joe',
'LastName' => 'Smith'
)
Failed idea was:
foreach($array as $key => $value)
{
$key = ucfirst($key);
}
This obviously will not work, because the array is not passed by reference. However, all these attempts also fail:
foreach(&$array as $key => $value)
{
$key = ucfirst($key);
}
foreach($array as &$key => $value)
{
$key = ucfirst($key);
}
Pretty much at my wits end with this one. I'm using Magento 1.9.0.1 CE, but that's pretty irrelevant for this problem. If you must know, the reason I have to do this is because I have a bunch of object that's I'm returning as an array to be assembled into a SOAP client. The API I'm using requires the keys to begin with a capital letter...however, I don't wish to capitalize the first letter of my object's variable names. Silly, I know, but we all answer to someone, and that someone wants it that way.
unset it first in case it is already in the proper format, otherwise you will remove what you just defined:
foreach($array as $key => $value)
{
unset($array[$key]);
$array[ucfirst($key)] = $value;
}
You can't modify the keys in a foreach, so you would need to unset the old one and create a new one. Here is another way:
$array = array_combine(array_map('ucfirst', array_keys($array)), $array);
Get the keys using array_keys
Apply ucfirst to the keys using array_map
Combine the new keys with the values using array_combine
The answers here are dangerous, in the event that the key isn't changed, the element is actually deleted from the array. Also, you could unknowingly overwrite an element that was already there.
You'll want to do some checks first:
foreach($array as $key => $value)
{
$newKey = ucfirst($key);
// does this key already exist in the array?
if(isset($array[$newKey])){
// yes, skip this to avoid overwritting an array element!
continue;
}
// Is the new key different from the old key?
if($key === $newKey){
// no, skip this since the key was already what we wanted.
continue;
}
$array[$newKey] = $value;
unset($array[$key]);
}
Of course, you'll probably want to combine these "if" statements with an "or" if you don't need to handle these situations differently.
This might work:
foreach($array as $key => $value) {
$newkey = ucfirst($key);
$array[$newkey] = $value;
unset($array[$key]);
}
but it is very risky to modify an array like this while you're looping on it. You might be better off to store the unsettable keys in another array, then have a separate loop to remove them from the original array.
And of course, this doesn't check for possible collisions in the aray, e.g. firstname -> FirstName, where FirstName already existed elsewhere in the array.
But in the end, it boils down to the fact that you can't "rename" a key. You can create a new one and delete the original, but you can't in-place modify the key, because the key IS the key to lookup an entry in the aray. changing the key's value necessarily changes what that key is pointing at.
Top of my head...
foreach($array as $key => $value){
$newKey = ucfirst($key);
$array[$newKey] = $value;
unset($array[$key]);
}
Slightly change your way of thinking. Instead of modifying an existing element, create a new one, and remove the old one.
If you use laravel or have Illuminate\Support somewhere in your dependencies, here's a chainable way:
>>> collect($array)
->keys()
->map(function ($key) {
return ucfirst($key);
})
->combine($array);
=> Illuminate\Support\Collection {#1389
all: [
"FirstName" => "Joe",
"LastName" => "Smith",
],
}
I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.
I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:
$main_array = array
(
[first_array] => array
(
['first_array1'] => product1
['first_arrayN'] => productN
)
[nth_array] => Array
(
[nth_array1] => date1
[nth_arrayN] => dateN
)
)
function getresult($something){
## some code
};
foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
$result["{$X_array}"]["{$key}"] = getresult($value);
echo $result["{$X_array}"]["{$key}"];
};
Any help would be appreciated!
foreach ($main_array as &$inner_array) {
foreach ($inner_array as &$value) {
$value = getresult($value);
echo $value;
}
}
unset($inner_array, $value);
Note the &, which makes the variable a reference and makes modifications reflect in the original array.
Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.
foreach($main_array AS $key=>$array){
foreach($array AS $newKey=>$val){
$array[$newKey] = getResult($val);
}
$main_array[$key] = $array;
}
Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}