This may be a newbie question, but I am not getting it .
I have an array say :
$form = Array
(
[Resource_ID] => 5251
)
and I want the output as
$form = Array
(
[Resource ID] => 5251
)
Underscore should be replaced by a space.
I tried
foreach($form as $key => $value)
{
$form [$key] = str_replace("_"," ",$form [$key]);
}
But this is not working !
Can anyone tell me where I am going wrong ?
You should use such code
foreach($form as $key => $value)
{
$abc[str_replace("_"," ",$key)] = $value;
// unset($abc[$key]); <- this could cause problem
}
or even
foreach($form as $key => $value)
{
$pos = strpos($key,'_');
if ($pos !== false) {
$abc[str_replace("_"," ",$key)] = $value;
unset($abc[$key]);
}
}
But in both cases you should consider what to do if you have keys: key 1 and key_1. It seems that you can override value or even remove it (depending if you will use unset or not).
Related
I have an array like below
Array
(
[0] => country-indonesia
[1] => country-myanmar
[2] => access-is_airport
[3] => heritage-is_seagypsy
)
From that array I want to make separate array only for [country] ,[access], [heritage]
So for that I have to check array value by text before '-'. I am not sure how to do it. so i can't apply code here. I just have the array in PHP
A modified answer, if you want to get the specific types only.
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
$types = ['country', 'heritage', 'access'];
foreach ($arr as $element) {
$fac = explode('-', $element);
foreach ($types as $type) {
if ($fac[0] === $type) {
$new_array[$type][] = $fac[1];
}
}
}
$country = $new_array['country'];
$access = $new_array['access'];
$heritage = $new_array['heritage'];
var_dump($new_array);
A simple and easy solution in 3 lines of code using array_walk
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
array_walk($arr, function($item) use (&$new_array){
//if(false === strpos($item, '-')) return;
list($key,$value) = explode('-', $item, 2);
$new_array[$key][] = $value;
});
print_r($new_array);
Gives this output:
Array
(
[country] => Array
(
[0] => indonesia
[1] => myanmar
)
[access] => Array
(
[0] => is_airport
)
[heritage] => Array
(
[0] => is_seagypsy
)
)
If you don't want empty and duplicate entries:
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
array_walk($arr, function($item) use (&$new_array){
if(false === strpos($item, '-')) return;
list($key,$value) = explode('-', $item, 2);
if(empty($value) || array_key_exists($key, $new_array) && in_array($value, $new_array[$key])) return;
$new_array[$key][] = $value;
});
print_r($new_array);
you can do it by using explode and in_array functions
<?php
$arr = ["country-indonesia","country-myanmar","access-is_airport","heritage-is_seagypsy"];
$newArr = array();
foreach($arr as $k=> $val){
$valArr = explode("-", $val);
if(!in_array($valArr[0], $newArr)){
$newArr[] = $valArr[0];
}
}
print_r($newArr);
?>
live demo
You need PHP's strpos() function.
Just loop through every element of the array and try something like:
if( strpos($array[$i], "heritage") != false )
{
// Found heritage, do something with it
}
(Rough example written from my cellphone while feeding baby, may have typos but it's the basics of what you need)
Read further here: http://php.net/manual/en/function.strpos.php
//first lets set a variable equal to our array for ease in working with i.e
// also create a new empty array to hold our filtered values
$countryArray = array();
$accessArray = array();
$heritageArray = array();
$oldArray = Array(country-indonesia, country-myanmar, access-is_airport, heritage-is_seagypsy);
//Next loop through our array i.e
for($x = 0; $x < count($oldArray); $x++){
// now filter through the array contents
$currentValue = $oldArray[$x];
// check whether the current index has any of the strings in it [country] ,[access], [heritage] using the method : strpos()
if(strpos($currentValue,'country')){
//if this particular value contains the keyword push it into our new country array //using the array_push() function.
array_push($countryArray,$currentValue);
}elseif(strpos($currentValue,'access')){
// else check for the access string in our current value
// once it's found the current value will be pushed to the $accessArray
array_push($accessArray,$currentValue);
}elseif(strpos($currentValue,'heritage')){
// check for the last string value i.e access. If found this too should be pushed to //the new heritage array i.e
array_push($heritageArray,$currentValue);
}else{
// do nothing
}
}
//I believe that should work: cheers hope
I have form with several fields I want to store those values in a session variable. Some of those fields should be 0 if the user doesn't fill them in.
A print_r($_POST) after submitting the form shows:
[report] => Array
(
[a_name] => Array
(
[0] =>
)
[a_id_card] => Array
(
[0] =>
)
[a_total] =>
Yet, after running the following PHP code, it seems that "a_name" and "a_id_card" are not interpreted as arrays. Any ideea why?
if (isset($_POST['submit'])) {
foreach ($_POST as $key => $value) {
if (!is_array($key) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}
think you want to write this - is_array($value)
$key is the string 'report'. So is_array($key) == false. However $_POST[$key] or $value is an array.
The key is never an array. It is always a scalar or string. The value, on the other hand, can be an array.
Maybe you want look only $_POST['report'], and check if 'value' is or not an array (not key):
if (isset($_POST['submit'])) {
foreach ($_POST['report'] as $key => $value) {
if (!is_array($value) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}
I have a multidimensional array like this which I converted from JSON:
Array (
[1] => Array (
[name] => Test
[id] => [1]
)
[2] => Array (
[name] => Hello
[id] => [2]
)
)
How can I return the value of id if name is equal to the one the user provided? (e.g if the user typed "Test", I want it to return "1")
Edit: Here's the code that works if anyone wants it:
$array = json_decode(file_get_contents("json.json"), true);
foreach($array as $item) {
if($item["name"] == "Test")
echo $item["id"];
}
The classical solution is to simply iterate over the array with foreach and check the name of each row. When it matches your search term you have found the id you are looking for, so break to stop searching and do something with that value.
If you are using PHP 5.5, a convenient solution that works well with less-than-huge data sets would be to use array_column:
$indexed = array_column($data, 'id', 'name');
echo $indexed['Test']; // 1
You can use this function
function searchObject($value,$index,$array) {
foreach ($array as $key => $val) {
if ($val[$index] === $value)
return $val;
}
return null;
}
$MyObject= searchObject("Hello","name",$MyArray);
$id = $MyObject["id"];
You can do it manually like, in some function:
function find($items, $something){
foreach($items as $item)
{
if ($item["name"] === $something)
return $item["id"];
}
return false;
}
here is the solution
$count = count($array);
$name = $_POST['name']; //the name which user provided
for($i=1;$i<=$count;$i++)
{
if($array[$i]['name']==$name)
{
echo $i;
break;
}
}
enjoy
Try this:
$name = "Test";
foreach($your_array as $arr){
if($arr['name'] == $name){
echo $arr['id'];
}
}
I have an array which contains a great deal of data, which has been generated from a JSON file. Most of the data is used to populateinput elements, but some of the keys contain hidden, default values to be used for calculations later.
The array looks something like this:
[name] => 'My App'
[default_E17] => 0.009
[default_H17] => 0.0236
[default_K17] => 50
[default_P17] => 0.0118
[default_E19] => 0.03
I want to loop over all default_* keys, and output them using HTML. Essentially, I want a foreach loop, but only for the keys whose format matches default_*. Does anyone know if this is possible?
Please note that the values in the array before [default_*] keys is variable length, so I cannot easily use an array_splice().
You use strpos($key, "default_") === 0 to show that it start with default_ and its not in the middle or end
$array = array();
$array['name'] = 'My App';
$array['default_E17'] = "0.009";
$array['default_H17'] = "0.0236";
$array['default_K17'] = "50";
$array['default_P17'] = "0.0118";
$array['default_E19'] = "0.03";
$array['E19_default_test'] = "1.03";
echo "<pre>";
* You can use foreach *
$list = array();
foreach ( $array as $key => $value ) {
if (strpos($key, "default_") === 0) {
$list[$key] = $value;
}
}
var_dump($list);
You can also use array_flip with array_filter
$array = array_flip(array_filter(array_flip($array),function($var) { return (strpos($var, "default_") === 0);}));
var_dump($array);
You can also use FilterIterator
class RemoveDefaultIterator extends FilterIterator {
public function accept() {
return (strpos($this->key(), "default_") === 0);
}
}
$list = new RemoveDefaultIterator(new ArrayIterator($array));
var_dump(iterator_to_array($list));
They would all Output
array
'default_E17' => string '0.009' (length=5)
'default_H17' => string '0.0236' (length=6)
'default_K17' => string '50' (length=2)
'default_P17' => string '0.0118' (length=6)
'default_E19' => string '0.03' (length=4)
foreach( $arr as $k => $v ) { //iterate the array
if( strpos($k, 'default_') !== FALSE ) //search if the key contains 'default_'
$default_values[] = $v; // if so, store the values for the 'default_' keys
}
Just iterate over your array
Foreach( $inputArray AS $key=>$val ) {
// check if key is the one we need
if( ... ) {
// it is - deal with it
}
}
depending of the keys you use if() can be simple substr() or regexp matching.
You can use a FilterIterator for this.
Its essetially the same as looping over the whole array, because that's the only way really, but it strips you from doing this in your productive loop, thus generating less noise.
Here's how:
class Default_FilterIterator extends FilterIterator
{
public function accept()
{
if (strpos($this->key(), 'default') === 0) {
return true;
}
return false;
}
}
$yourArray = array('default_stuff' => 'foo', 'otherstuff' => 'bar');
$filterdArray = new Default_FilterIterator(new ArrayIterator($yourArray));
foreach ($filteredArray as $key => $value) {
//deal only with default values here
}
foreach ($your_array as $key => $value) {
// check if the $key starst with 'default_'
if (substr($key, 0, 8) == "default_") {
//do your thing...
echo "<input type='text' value='" . $value . "'>";
}
}
I have the following code:
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$array_30 = array
(
'0'=>1,
1=>'2',
2=>'3'
);
$array_31 = array
(
'0'=>4,
'1'=>'5',
'2'=>'6'
);
I need to make it an array and insert the array_30 and array_31 into a DB.
foreach($rt1 as $value){
$rt2[] = $value['0'];
}
The question was updated, so here is an updated answer. Quick check, you should really try and update this to whatever more generic purpose you have, but as a proof of concept, a runnable example:
<?php
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$finalArrays = array();
foreach($rt1 as $key=>$value){
if(is_array($value)){
$array_name = "array_".substr($key,-2);
${$array_name}[] = $value['0'];
}
}
var_dump($array_30);
var_dump($array_31);
?>
will output the two arrays with the numbers 1,2,3 and 4,5,6 respectivily
i assume you want to join the values of each of the second-level arrays, in which case:
$result = array();
foreach ($rt1 as $arr) {
foreach ($arr as $item) {
$result[] = $item;
}
}
Inspired by Nanne (which reminded me of dynamically naming variables), this solution will work with every identifier after the \#, regardless of its length:
foreach ( $rt1 as $key => $value )
{
if ( false == strpos($key, '#') ) // skip keys without #
{
continue;
}
// the part after the # is our identity
list(,$identity) = explode('#', $key);
${'array_'.$identity}[] = $rt1[$key]['0'];
}
Presuming that this is your actual code, probably you will need to copy the array somewhere using foreach and afterwards create the new array as you wish:
foreach($arr as $key => $value) {
$arr[$key] = 1;
}