Change value of multidimensional php array with function result - php

I have the feeling I am missing something simple. I need to change the value of a key in a multi dimensional array based on the result of a function. Here is my array $exports
Array (
[0] => Array (
[captain] => Yes
[uniform] => 3
[fname] => Sally
[lname] => Smith
[position1] => OH
[position2] =>
[position3] =>
[bio] =>
[classyear] => 2015
[hft] => 5
[hin] => 7
)
[1] => Array (
[captain] => Yes
[uniform] => 2
[fname] => Danielle
[lname] => Smith
[position1] => L
[position2] => S
[position3] => OH
[bio] =>
[classyear] => 2016
[hft] => 5
[hin] => 2
)
[2] => Array (
[captain] => No
[uniform] => 4
[fname] => Erica
[lname] => Smith
[position1] => RS
[position2] =>
[position3] =>
[bio] =>
[classyear] => 2018
[hft] => 5
[hin] => 9
)
)
This is the code I am using.
foreach($exports as $key => &$value)
{
foreach($value as $key1 => &$value1)
{
if( $key1 == "classyear") $value1=JHtml::_('helper.gradenumber', $value1, $season);
}
unset($value1);
}
unset($value);
return $exports;
This is within Joomla so the JHml line is my function. If I replace this with a string, then my array is updated correctly, but using the function, my classyear key is empty. I have tested and know the function is returning the correct value.

It seems like what you have should mostly work, but in this part:
$value1=JHtml::_('helper.gradenumber', $value1['classyear'], $season)
I think $value1['classyear'] should just be $value1,
because if( $key1 == "classyear") then $value1 will just be a number.
Also, if you are seeing all the results of the classyear function first, you may have it echoing the value instead of returning it.
You could probably use array_walk for this.
array_walk($exports, function (&$value) use ($season) {
$value['classyear'] = JHtml::_(
'helper.gradenumber', $value['classyear'], $season);
});

You referenced to your $value and $value1, and then unset them. Do not use references, instead of that, update the value like this:
foreach ($exports as $key => $value) {
foreach ($value as $key1 => $value1) {
if ($key1 == "classyear") {
$exports[$key1] = JHtml::_('helper.gradenumber', $export['classyear'], $season);
}
}
}

Can use array_key_exists() to check key exist or not. No need to use nested foreach() . Example:
$finalArray = array();
foreach($exports as $key => $value)
{
if(array_key_exists("classyear", $value)){
$value["classyear"] = JHtml::_('helper.gradenumber', $export['classyear'], $season);
}
$finalArray[] = $value;
}

I haven't tested this code, but array_walk_recursive() seems to me to be the way to handle this:
function changeKey(&$item, $key) {
if($key == 'classyear') {
$classYear = $item;
$item = JHtml::_('helper.gradenumber', $classYear, $season);
}
}
array_walk_recursive($exports, 'changeKey');

Related

How to unset numeric index elements from a PHP array?

I have a collection of array it contains both numeric index as well as non numeric. I want to unset all the numeric indexes.
My array is something like this .
Array
(
[554] => Array
(
[0] => 554
[1] => Jiaqi Zheng
[2] => Female
[3] => 28
[4] => Table Tennis
[5] =>
[6] =>
[7] =>
[8] =>
[rank] => 554
[athlet_name] => Jiaqi Zheng
[gender] => Female
[sport] => Table Tennis
)
[555] => Array
(
[0] => 555
[1] => Zach Ziemek
[2] => Male
[3] => 23
[4] => Athletics
[5] =>
[6] =>
[7] =>
[8] =>
[rank] => 555
[athlet_name] => Zach Ziemek
[gender] => Male
[sport] => Athletics
)
)
Here i have to unset all the numeric index .
I used unset like this and its working fine for me .
unset(
$history_years_wise_country_wise_details_arr[ $history_years_wise_country_wise_details_info[0]][0],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][1],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][2],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][3],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][4],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][5],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][6],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][7],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][8]
);
Is there any way I will reduce the lines of codes? here 0 to 8 are in one series.
Can I unset all index in one line of code , as all are numeric?
Is it possible to use regular expression instead?
I want something like
unset(
$history_years_wise_country_wise_details_arr[ $history_years_wise_country_wise_details_info[0]][anything_which_will_take_index_from_0_to_8]);
Any suggestions?
Thank you
You could use array_filter() with is_string() function as its callback function:
$array = array_filter($array, 'is_string', ARRAY_FILTER_USE_KEY);
Use looping.
foreach ($array as $key => $value) {
if (is_numeric ($key)) {
unset($array [$key]);
}
}
Or use array_filter
$filtered = array_filter(
$array,
function ($key) {
return !is_numeric($key);
},
ARRAY_FILTER_USE_KEY
);
You shoud used foreach loop with is_numeric function like
foreach ($your_array as $key => $value) {
if (!is_numeric($key)) {
unset($arr[$key]);
}
}
i think there is no need of any regular expression
Since you have array inside array first you need to use array_map() and then traverse through array using array_filter(),
considering $array as your array:
$resultData = array_map([$this, 'allData'], $array);
public function allData($data)
{
$numericKeys = array_filter(array_keys($data), function ($k) {
return is_int($k);
});
// Updated Code
$arrayKeys = array_diff(array_keys($data),$numericKeys);
return array_intersect_key($data,array_flip($arrayKeys));
}

How get value from array

I have an array like
Array
(
[0] => stdClass Object
(
[id] => 1
[org_name] => name
[field_name] => fullname
[new_name] => Name
[index] => 3
[modified] => 2016-05-17 10:45:17
)
[1] => stdClass Object
(
[id] => 3
[org_name] => reception_no
[field_name] => reception_no
[new_name] => Reception No.
[index] => 1
[modified] => 2016-05-17 10:45:17
)
[2] => stdClass Object
(
[id] => 4
[org_name] => pno
[field_name] => pno
[new_name] => Personel No.
[index] => 0
[modified] => 2016-05-17 10:45:17
)
and i want for example
where object has 'pno' get value of 'index' in this example for example '0'
is there possible to do that ?
foreach ($arr as $items)
{
if ($items->org_name=='pno')
$index=$items->index;
}
As i am asking you about the pno, I think it was the first index like 0,1,2..., But after some conversation this is clear that it is inside the sub array.
So you need a loop here and check for the pno, if matched then echo the index. Let your array is $array
foreach ($array as $key => $val){
if($val->org_name == 'pno'){
echo $index = $val->index;
break;
}
}
yes it is possible try this
var_dump($arr[0]->index);
OR
print_r($arr->index['0']);
You can use array_search
$key1 = array_search('pno', array_column($your_array, 'field_name'));
$key2 = array_search('pno', array_column($your_array, 'org_name'));
Use array_search since you may not know the index
array_search
Tested with ur Array
$array = array(
array('id'=>1,'org_name'=>'name','field_name'=>'fullname','new_name'=>'Name','index'=>3,'modified'=>'2016-05-17 10:45:17'),
array('id'=>3,'org_name'=>'reception_no','field_name'=>'reception_no','new_name'=>'Reception No.','index'=>1,'modified'=>'2016-05-17 10:45:17'),
array('id'=>4,'org_name'=>'pno','field_name'=>'pno','new_name'=>'Personel No.','index'=>0,'modified'=>'2016-05-17 10:45:17')
);
This Code should do what u want
$index = '';
foreach($array as $key => $value)
{
if($value['org_name']=='pno')
{
$index = $value['index'];
}
}
print $index;
Script only Loops through ur Array and sets $index on the last found pno index value
U can check $index in an IF, if ist empty.

Why is the value of array key not getting updated?

I have an array called $test_data, and I want to update a key ['test_duration']. However, I am unable to do this update. Consider the following array:
Array
(
[0] => Array
(
[test_id] => 1116
[test_name] => ques stats
[test_no_questions] => 50
[test_duration] => 28800
)
[1] => Array
(
[test_id] => 1112
[test_name] => Own Test 1
[test_no_questions] => 2
[test_duration] => 7200
)
)
I tried the following, but it didn't work out:
foreach ($test_data as $key => $value) {
$value[$key]['test_duration'] = ConvertTimeStampToTimeFormate($value['test_duration']);
}
If I print the array after this manipulation, it's printing the same array as before. What is the problem here?
update $test_data instead of $value
foreach ($test_data as $key => $value) {
$test_data[$key]['test_duration'] = ConvertTimeStampToTimeFormate($value['test_duration']);
}
You need to nest a furthermore.
foreach ($test_data as $arr)
{
foreach($arr as $k=>$v)
{
$value[$k]['test_duration'] = ConvertTimeStampToTimeFormate($value['test_duration']);
}
}
Use like this,
foreach ($test_data as $key => $value) {
$test_data[$key]['test_duration'] = ConvertTimeStampToTimeFormate($value['test_duration']);
}

Problems with mutiple array in foreach loops

This is my first question here so i dont exactly know the normal style.
I have a problem with multiple arrays. My arrays are sorted this way:
Array
(
[count] => 2
[gebruikerData] => Array
(
[gebruiker1] => Array
(
[merken] => Array
(
[0] => merk1
[1] => merk10
[2] => merk19
)
[loginnaam] => testfasdfasd
[geslacht] => Man
[persoonlijkheidsType] => TEST
[beschrijving] => fasdfasdfasd
[gebruikerID] => 19
[leeftijd] => 21
)
[gebruiker2] => Array
(
[merken] => Array
(
[0] => merk1
[1] => merk9
[2] => merk36
)
[loginnaam] => test1233
[geslacht] => Man
[persoonlijkheidsType] => TEST
[beschrijving] => safasfd
[gebruikerID] => 20
[leeftijd] => 21
)
)
)
I need to retrieve all the information in this array. There can be as many fields gebruiker(number) as the database output, so i tried to use multiple foreach loops in eachother. My problem is that it is not possible to use the key from one foreach loop as index in another foreach loop like this:
foreach ($gebruikerData as $key => $value)
{
foreach ($key as $key2 => $value2)
{
echo $key2;
}
}
Does anyone have another idea how i could retrieve the information from the array? Or is if could use my own way with a slight change?
Try like this
foreach ($gebruikerData as $key => $value)
{
if(is_array($key))
{
foreach ($key as $key2 => $value2)
{
if(is_array($key2))
{
foreach($key2 as $key3=>$value3)
echo $key3.'-'.$value3;
}
else
echo $key2.'-'.$value2;
}
}
else
echo $key.'-'.$value;
}
Check for the $key is "array or not" each time,if it is array then it will fo to for loop orelse it will echo it directly

Output two-dimensional array

Ok, I'm still struggling with my arrays... I have created a two-dimensional array and saved into a session to get results on another page: $_SESSION['myARRAY']
print_r($_SESSION['myARRAY']);
// will output:
Array ( [Car] => Array ( [0] => 1 [1] => 9 [2] => 0 )
[Truck] => Array ( [0] => 2 [1] => 10 [2] => 0 )
[Bus] => Array ( [0] => 1 [1] => 8 [2] => 2 ))
Now I need to output the data into the following format:
$xls->addRow(Array("Car",1,9,0));
$xls->addRow(Array("Truck",2,10,0));
$xls->addRow(Array("Bus",1,8,2));
I tried to do something like this:
foreach($_SESSION['myARRAY'] AS $key => $value) {
$arr[$key] = $key;
foreach($value AS $k => $v) {
$arr[$key] = $v;
}
$xls->addRow($arr[$key]);
}
but it did not really work. I think I'm close but not quite there...
$value is already an array. Now you only need to prepend the $key to it. You could use array_unshift:
foreach($_SESSION['myARRAY'] AS $key => $value) {
array_unshift($value, $key);
$xls->addRow($value);
}
Of course if you do this more than once, you should consider storing the consolidated array.
I'd probably use array_unshift as it seems like a more appropriate way to solve this problem, but you could also do it like:
foreach($_SESSION['myARRAY'] AS $key => $value) {
$xls->addRow(array_merge(array($key), $value));
}

Categories