I need some help with another PHP problem I am working on. I won't be posting the exact question, as I'd prefer to try and apply the knowledge I get from here to solve my problem.
First:
I have an associative array. I must loop through the array to find the array values which have keys that begin with a specific string and push both the key and value to an output array.
eg:
- Loop through the below array & push all elements which have a key beginning with "edible_" to an output array:
$assoc_array = array(
'edible_fruit' => 'apple',
'animal' => 'cat',
'edible_veg' => 'pumpkin',
'number' => '23',
'city' => 'Cape Town',
'edible_berry' => 'blueberry',
'color' => 'blue'
);
Would this work?
$result = array();
foreach ($assoc_array as $key => $value) {
if (substr($key, 0, 7) == "edible_") {
array_push($result, $value);
}
}
print_r($result);
Second:
How would I remove "edible_" from the output array's keys? With this second bit I have no idea where to even begin!
Third:
I've managed to figure out the above with all your help, thank you! Now I just need to find out how I would print each element on a new line with a date & timestamp at the end of each line? I've got this (doesn't seem to be working):
while (list($key, $value) = each($output)) {
print_r("$key => $value" . date("y/m/d G.i:s", time()) . "<br>");
}
First of your code will work.
To remove edible_ from the key you could use explode() -
$keyParts = explode('_', $key);
$newKey = $keyParts[1];
You will have to add the new keys to the array, which you're not doing now.
foreach ($assoc_array as $key => $value) {
if (substr($key, 0, 7) == "edible_") {
$keyParts = explode('_', $key);
$newKey = $keyParts[1];
$result[$newKey] = $value;
}
}
This would be my approach:
foreach($assoc_array as $key => $value) {
if(preg_match("/^edible_/",$key)) {
$result[preg_replace("/^edible_/","",$key)] = $value;
}
}
use preg_match to check if the key starts with what you are looking for and use preg_replace to remove the string from the beginning (^) of the key :)
Input ($assoc_array):
Array
(
[edible_fruit] => apple
[animal] => cat
[edible_veg] => pumpkin
[number] => 23
[city] => Cape Town
[edible_berry] => blueberry
[color] => blue
)
Output ($result):
Array
(
[fruit] => apple
[veg] => pumpkin
[berry] => blueberry
)
First: yes, that would work, however I would rewrite it a bit:
foreach ($assoc_array as $key => $value) {
if (strpos($key, 'edible_') === 0) {
$result[] = $value;
}
}
Regarding Second: You are asking how to remove the key from the output array. However you did not even push the key into the output array, you only pushed the value. If you'd like to also push the key, you should do it like this:
$result[$key] = $value;
But since you haven't done that, there's no need to remove the key.
If you however meant removing the edible_ part of the key from the $assoc_array, you'd just need to add a line to the loop and pass the key by reference by adding a &:
foreach ($assoc_array as &$key => $value) {
if (strpos($key, 'edible_') === 0) {
$key = str_replace('edible_', '', $key)
$result[] = $value;
}
}
Edit: As OP told me in comments, she wants to push the key without the edible part. So just do it like this:
foreach ($assoc_array as $key => $value) {
if (strpos($key, 'edible_') === 0) {
$key = str_replace('edible_', '', $key)
$result[$key] = $value;
}
}
This should work for you:
First I remove all elements, which doesn't have edible_ at the start of the key with array_diff_ukey(). After this I simply array_combine() the elements with they keys, where I remove the prefix with array_map() and substr().
<?php
$assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');
//remove elemnts
$result = array_diff_ukey($assoc_array, ["edible_" => ""], function($k1, $k2){
return substr($k1, 0, 7) == $k2;
});
//change keys
$result = array_combine(
array_map(function($v){
return substr($v, 7);
}, array_keys($result)),
$result);
print_r($result);
?>
output:
Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )
You can loop through the array and search if the key has the string that you can eliminate and make your $newArray
<?php
$assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');
$search = 'edible_';
$newArray = array();
#First and Second Step
foreach($assoc_array as $key => $value) {
if(strpos($key, "edible_") === 0) {
$newArray[substr($key, 7)] = $value;
}
}
print_r($newArray);
echo "<br>\n";
#Third Step
foreach($newArray as $key => $value) {
echo "$key => $value " . date("y/m/d G.i:s", time()) . "<br>\n";
}
Output:
#First and Second Step
Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )
#Third Step
fruit => apple 15/04/10 3.02:16
veg => pumpkin 15/04/10 3.02:16
berry => blueberry 15/04/10 3.02:16
Related
I have an array, looking like this:
[lund] => Array
(
[69] => foo
)
[berlin] => Array
(
[138] => foox2
)
[tokyo] => Array
(
[180] => foox2
[109] => Big entrance
[73] => foo
)
The thing is that there were duplicate keys, so I re-arranged them so I can search more specifically, I thought.
Previously I could just
$key = array_search('foo', $array);
to get the key but now I don't know how.
Question: I need key for value foo, from tokyo. How do I do that?
You can get all keys and value of foo by using this:
foreach ($array as $key => $value) {
$newArr[$key] = array_search('foo', $value);
}
print_r(array_filter($newArr));
Result is:
Array
(
[lund] => 69
[tokyo] => 109
)
If you don't mind about the hard code than you can use this:
array_search('foo', $array['tokyo']);
It just a simple example, you can modify it as per your requirement.
Try this
$a = array(
"land"=> array("69"=>"foo"),
"land1"=> array("138"=>"foo1"),
"land2"=> array('180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'),
);
//print_r($a);
$reply = search_in_array($a, "foo");
print_r($reply);
function search_in_array($a, $search)
{
$result = array();
foreach($a as $key1 => $array ) {
foreach($array as $k => $value) {
if($value == "$search") {
array_push($result,"{$key1}=>{$k}");
breck;
}
}
}
return $result;
}
This function will return the key or null if the search value is not found.
function search($searchKey, $searchValue, $searchArr)
{
foreach ($searchArr as $key => $value) {
if ($key == $searchKey && in_array($searchValue, $value)) {
$results = array_search($searchValue, $value);
}
}
return isset($results) ? $results : null;
}
// var_dump(search('tokyo', 'foo', $array));
Since Question: I need key for value foo, from tokyo. How do i do that?
$key = array_search('foo', $array['tokyo']);
As a function:
function getKey($keyword, $city, $array) {
return array_search($keyword, $array[$city]);
}
// PS. Might be a good idea to wrap this array in an object and make getKey an object method.
If you want to get all cities (for example to loop through them):
$cities = array_keys($array);
I created solution using array iterator. Have a look on below solution:
$array = array(
'lund' => array
(
'69' => 'foo'
),
'berlin' => array
(
'138' => 'foox2'
),
'tokyo' => array
(
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
)
);
$main_key = 'tokyo'; //key of array
$search_value = 'foo'; //value which need to be search
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if ($value == $search_value) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
if(in_array($main_key, $key_paths) !== false) {
echo "'{$key}' have '{$value}' value which traverse path is: " . implode(' -> ', $key_paths) . '<br>';
}
}
}
you can change value of $main_key and $serch_value according to your parameter. hope this will help you.
<?php
$lund = [
'69' => 'foo'
];
$berlin = [
'138' => 'foox2'
];
$tokyo = [
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
];
$array = [
$lund,
$berlin,
$tokyo
];
echo $array[2]['180']; // outputs 'foox2' from $tokyo array
?>
If you want to get key by specific key and value then your code should be:
function search_array($array, $key, $value)
{
if(is_array($array[$key])) {
return array_search($value, $array[$key]);
}
}
echo search_array($arr, 'tokyo', 'foo');
try this:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$array=array("lund" => array
(
69 => "foo"
),
"berlin" => array
(
138 => "foox2"
),
"tokyo" => array
(
180 => "foox2",
109 => "Big entrance",
73 => "foo"
));
function search($array, $arrkey1, $arrvalue2){
foreach($array as $arrkey=>$arrvalue){
if($arrkey == $arrkey1){
foreach($arrvalue as $arrkey=>$arrvalue){
if(preg_match("/$arrvalue/i",$arrvalue2))
return $arrkey;
}
}
}
}
$result=search($array, "tokyo", "foo"); //$array=array; tokyo="inside array to check"; foo="value" to check
echo $result;
You need to loop through array, since its 2 dimensional in this case. And then find corresponding value.
foreach($arr as $key1 => $key2 ) {
foreach($key2 as $k => $value) {
if($value == "foo") {
echo "{$k} => {$value}";
}
}
}
This example match key with $value, but you can do match with $k also, which in this case is $key2.
PHP newb trying to find the value from array2 in the key in array1 and where they match do something to the value of array1. Pretty sure this is easy but am not massively familiar with php. Any help would be appreciated. Have been tinkering with array_search, in_array but unable to make anything work.
Hoped for result is where the value of array2 is found in the key of array1 the value of the matched key value pair would be divided by 2.
$array1 = Array (
[shore_anchor] => 0
[inter_anchor] => 0
[offshore_anchor] => 0
[offshore_gear] => 5
[shore_infrastructure] => 0
[inter_infrastructure] => 0
[coastal_vessel] => 5
[offshore_vessel] => 5 );
$array2 = Array ( [0] => infrastructure [1] => anchor );
foreach($array2 as $key1 => $val1){
foreach ($array1 as $key => $value) {
if ($key1 == $key){
echo "$key => $value <br />";
}}}}
I think this might be it, but comments or efficiencies are welcome.
$result = array_flip($array2);
foreach($result as $needle => $val1){
foreach ($array1 as $haystack => $val2) {
if (strpos($haystack, $needle) !== false) {
echo "$haystack => $val2\n";
}
}
}
one way:
<?php
$array1 = Array(
'shore_anchor'=>0,
'inter_anchor'=>0,
'offshore_anchor'=>0,
'offshore_gear'=>5,
'shore_infrastructure'=>0,
'inter_infrastructure'=>0,
'coastal_vessel'=>5,
'offshore_vessel'=>5
);
$array2 = Array(
'0'=>'infrastructure',
'1'=>'anchor'
);
foreach ($array1 as $key=>$value){
$x = explode('_',$key);
if (in_array($x[0],$array2) || in_array($x[1],$array2)){
echo "$key => $value <br />";
}
}
// for PHP 5.6.0 +
$match = '#' . implode('|',$array2) . '#';
$x = array_filter($array1,function ($key) use ($match){
return preg_match($match,$key);
},ARRAY_FILTER_USE_KEY);
foreach ($x as $key=>$value){
echo "$key => $value <br />";
}
UPDATE: someone edited my question incorrectly, but it's fixed now
Let's say I have the following associative array:
Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)
You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:
Array ( [Postponement no issue for Man Utd] => 18 )
Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".
In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.
Is this possible and how? Thanks in advance.
Depending on the size of your data this may not be feasible. There is almost certainly a more optimal solution, but this works:
<?php
$array = array(
'Postponement no issue for Man Utd (BBC)' => 8,
'Postponement no issue for Man Utd' => 7,
'Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday\'s game at Chelsea being ...' => 3
);
$keys = array_keys($array);
usort($keys, 'lengthCmp');
$flippedKeys = array_flip($keys);
$data = array();
foreach ($keys as $k => $v)
{
$sum = 0;
foreach ($array as $key => $val)
{
if (stripos($key, $v) !== FALSE)
{
$sum += $val;
unset($array[$key]);
unset($keys[$flippedKeys[$v]]);
}
}
$data[$v] = $sum;
}
foreach ($data as $key => $val)
{
if ($val == 0)
unset($data[$key]);
}
var_dump($data);
function lengthCmp($a, $b)
{
return strlen($a) - strlen($b);
}
?>
Output:
array(1) {["Postponement no issue for Man Utd"] => int(18)}
And with this data set:
$array = array(
'test test' => 1,
'Postponement no issue for Man Utd (BBC)' => 8,
'Postponement no issue for Man Utd' => 7,
'Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday\'s game at Chelsea being ...' => 3,
'test' => 1,
'not here' => 1,
'another test' => 1
);
Output:
array(3) {
["test"] => int(3)
["not here"] => int(1)
["Postponement no issue for Man Utd"] => int(18)
}
foreach($array as $k1 => $v1)
foreach($array as $k2 => $v2)
if(strpos($k2, $k1) !== false) // or === 0
$result[$k1] = (isset($result[$k1]) ? $result[$k1] : 0) + $v2;
untested
A simple approach could be:
$original_array = array(...); // The original array with keys and values
asort($original_array); // Sort the array by its keys
$clean_array = array();
foreach ($original_array as $key => $value)
{
foreach (array_keys($clean_array) as $clean_key)
{
$found = false;
if (preg_match('/'.preg_quote($clean_key).'/', $key))
{
$clean_array[$clean_key] += $value;
$found = true;
break;
}
if (!$found) $clean_array[$key] = $value;
}
}
Ok... the only way to do this is to iterate through the array twice, and have a function compare them:
foreach ($my_array as $key1 => $value1) {
foreach ($my_array as $key2 => $value2) {
if ($key1 != $key2) { // don't compare them if they're the same
if (compareKeys($key1,$key2)) {
$my_array[$key1] += $value2;
unset($my_array[$key2]);
}
}
}
}
Then your compareKeys function could look something like this:
function compareKeys($val1,$val2) {
return (strpos($val1,$val2)!==false);
}
I have the following array
$group= array(
[0] => 'apple',
[1] => 'orange',
[2] => 'gorilla'
);
I run the array group through an for each function and when the loop hits values of gorilla I want it to spit out the index of gorilla
foreach ($group as $key) {
if ($key == gorilla){
echo //<------ the index of gorilla
}
}
You can use array_search function to get the key for specified value:
$key = array_search('gorilla', $group);
foreach( $group as $index => $value) {
if ($value == "gorilla")
{
echo "The index is: $index";
}
}
array_search — Searches the array for a given value and returns the corresponding key if successful
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
foreach($group as $key => $value) {
if ($value=='gorilla') {
echo $key;
}
}
The foreach($c as $k => $v) syntax is similar to the foreach($c as $v) syntax, but it puts the corresponding keys/indices in $k (or whatever variable is placed there) for each value $v in the collection.
However, if you're just looking for the index of a single value, array_search() may be simpler. If you're looking for indices for many values, stick with the foreach.
Try this:
foreach ($group as $key => $value)
{
echo "$key points to $value";
}
foreach documentation on php.net
In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.