How to get array values data in PHP - php

I need small doubt in PHP. how to get below PHP array data in to variables.
$arraydata = Array
(
[366] => 1084569.5892969
[181TO365] => -2128157.619635
[121TO180] => -59235.780429687
[91TO120] => -266089.29
[61TO90] => -56390
[0TO60] => 8212872.9800098
)
This is my array output data.i need to get these data in to as variables like below.
$366data= 1084569.5892969;
$181TO365data = -2128157.619635;
$121TO180data = -59235.780429687;
$91TO120data = -266089.29;
$61TO90data = -56390;
$0TO60data = 8212872.9800098;
Like this variables get data . Can anyone help

Apart from the fact that PHP variables cannot start with a number (_ or letter) you can just loop over it like so:
<?php
foreach( $array as $key => $value ) {
$$key = $value;
}
The $$ before key means that you assign the value of $key to a variable with that name. But you probably to prefix it with an _ to make this work.
For example:
<?php
foreach( $array as $key => $value ) {
$prefixed = '_' . $key;
$$prefixed = $value;
}
Why do you want this by the way?

Related

PHP dynamic array name with loop

I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}

How to make key value by explode and arrange matching key values into one key?

I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!

How can I rename some keys in a PHP array using another associative array?

Given a data array ...
$data_array = array (
"old_name_of_item" => "Item One!"
);
... and a rename array ...
$rename_array = array (
"old_name_of_item" => "new_name_of_item"
);
... I would like to produce an output like this:
Array
(
[new_name_of_item] => Item One!
)
I have written the following function, and while it works fine, I feel like I'm missing some features of PHP.
function rename_keys($array, $rename_array) {
foreach( $array as $original_key => $value) {
foreach( $rename_array as $key => $replace ) {
if ($original_key == $key) {
$array[$replace] = $value;
unset($array[$original_key]);
}
}
}
return $array;
}
Does PHP offer built-in functions to help with this common problem? Thanks!
You only have to go through the array once:
function rename_keys($array, $rename_array) {
foreach ( $rename_array as $original_key => $value ) {
if (isset($array[$original_key])) {
$array[$rename_array[$original_key]] = $array[$original_key];
unset($array[$original_key]);
}
}
}
This assumes, of course, that both arrays are correctly filled (unique values for the replacement keys).
Edit: only replace if a corresponding element exists in $rename_array.
Edit 2: only goes through $rename_array
Second time today. This one is easier:
$data_array = array_combine(
str_replace(array_keys($rename_array), $rename_array, array_keys($data_array)), $data_array);

PHP unset array key for empty value not working

For some reason I can not determine why empty array keys aren't being unset. Here is what I have...
PHP
<?php
$attachments = explode('|',$_POST['post_attachments']);
foreach($attachments as $k=>$v)
{
echo 'k = \''.$v."'\n";
if ($v=='')
{
unset($k);
}
}
print_r($attachments);die();
?>
Output
k = ''
k = 'secret_afound.gif'
k = 'secret_aunlocked.gif'
Array (
[0] =>
[1] => secret_afound.gif
[2] => secret_aunlocked.gif
)
You should do:
foreach ($attachments as $k=>$v) {
//...magic
unset($attachments[$k]);
}
You are only unsetting $k, not the element in attachments. Try unset($attachments[$k]);
I believe you should use unset($attachments[$k]);.
In this scenario I like to think of $k as a temporary variable. Even though you unset it you didn't alter $attachments in anyway.

foreach and multidimensional array

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;
}

Categories