how to change illegal characters in php extract function? - php

I needed to extract key-value pairs from the following array into variables
$data = array(
'Quotation.id' => 1,
'Quotation.project_id' => 2
);
extract($data);
Because the . is an illegal character in PHP, no extra variables are defined when I run extract.
I would like to somehow remove the dots and change the entire field into a camelCase. Meaning to say, without knowing in advance the keys in $data, I would like to somehow get back as newly-defined variables:
$quotationId = 1;
$quotationProjectId = 2;
How do I accomplish this?
Please ignore situations where the newly-defined variables may clash with existing variables. Assume this will not happen.

There is probably an easier way with regular expressions, but this is how I would do it:
foreach ($data AS $k => $v) {
$key = str_replace(' ', '', ucwords(str_replace('.', ' ', $k)));
${$key} = $v;
}

You may try this
<?php
$data = array(
'Quotation.id' => 1,
'Quotation.project_id' => 2
);
foreach($data as $key=>$value) {
$keys = array_map('ucfirst',preg_split( "/(\._)/", $key ));
$newKey = implode($keys);
unset($data[$key]);
$data[$newKey] = $value;
}
export($data);
?>

Related

How to match and replace one array values to another array keys if they both start with the same letters?

I have two arrays:
$array_one = array('AA','BB','CC');
And:
$replacement_keys = array
(
""=>null,
"BFC"=>'john',
"ASD"=>'sara',
"CSD"=>'garry'
);
So far I've tried
array_combine and to make a loop and try to search for values but can't really find a solution to match the keys of the second array with the values of the first one and replace it.
My goal is to make a final output:
$new_array = array
(
''=>null,
'BB' => 'john',
'AA' => 'sara',
'CC' => 'garry'
);
In other words to find a matching first letter and than replace the key with the value of the first array.
Any and all help will be highly appreciated.
Here is a solution keeping both $replacement_keys and $array_one intact
$tempArray = array_map(function($value){return substr($value,0,1);}, $array_one);
//we will get an array with only the first characters
$new_array = [];
foreach($replacement_keys as $key => $replacement_key) {
$index = array_search(substr($key, 0, 1), $tempArray);
if ($index !== false) {
$new_array[$array_one[$index]] = $replacement_key;
} else {
$new_array[$key] = $replacement_key;
}
}
Here is a link https://3v4l.org/fuHSu
You can approach like this by using foreach with in_array
$a1 = array('AA','BB','CC');
$a2 = array(""=>null,"BFC"=>'john',"ASD"=>'sara',"CSD"=>'garry');
$r = [];
foreach($a2 as $k => $v){
$split = str_split($k)[0];
$split .= $split;
in_array($split, $a1) ? ($r[$split] = $v) : ($r[$k] = $v);
}
Working example :- https://3v4l.org/ffRWY

How implode correctly this array?

I have this array ($recip):
Array
(
[0] => 393451234567
[1] => 393479876543
)
SMS API provider requires numbers in this format:
recipients[]=393334455666&recipients[]=393334455667
With
$recipients = implode('&recipients[]=',$recip);
I can obtain only this:
393471234567&recipients[]=393459876543
Missing first one "recipients[]" (overall, first one no require the "&" at all).
Just append the initial recipients[]= to the front of your string:
$recipients = 'recipients[]=' . implode('&recipients[]=',$recip);
Another option:
foreach ($array as $key => $value){
$array[$key] = (($key == 0) ? '' : '&').'recipients[]='.$value;
}
$result = implode('',$array);
A foreach loop allows you to conctenate your string. I include a check to avoid appending the & on the first part of the string.
Pointing this out as an option, but the other way is simpler!
Try this:
vsprintf('recipients[]=%s&recipients[]=%s', $recip);
Another option
foreach ($recip as $ip){
$array[] = 'recipients[]=' . $ip;
}
$result = implode('&',$array);

PHP arrays & variable variables

With an array $s_filters that looks like this (many different keys possible):
Array
(
[genders] => m
[ages] => 11-12,13-15
)
How can I programatically convert this array to this:
$gender = array('m');
$ages = array('11-12','13-15');
So basically loop through $s_filters and create new arrays the names of which is the key and the values should explode on ",";
I tried using variable variables:
foreach( $s_filters as $key => $value )
{
$$key = array();
$$key[] = $value;
print_r($$key);
}
But this gives me cannot use [] for reading errors. Am I on the right track?
The following code takes a different approach on what you're trying to achieve. It first uses the extract function to convert the array to local variables, then loops though those new variables and explodes them:
extract($s_filters);
foreach(array_keys($s_filters) as $key)
{
${$key} = explode(",", ${$key});
}
$s_filters = Array
(
"genders" => "m",
"ages" => "11-12,13-15"
);
foreach($s_filters as $key=>$value)
{
${$key} = explode(',', $value);
}
header("Content-Type: text/plain");
print_r($genders);
print_r($ages);
$gender = $arr['gender'];
What you want there is unreadable, hard to debug, and overall a bad practice. It definitely can be handled better.

php exploded associative array problem

I have php script as below;
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$array = explode(",", $ages2);
echo $array["Peter"];
echo $ages["Peter"];
In this case, echo $ages["Peter"]; is working well, but echo $array["Peter"]; is not working. Can anybody solve this please..
Thanks in advance.
blasteralfred
You'll have to go in two steps :
First, explode using ', ', as a separator ; to get pieces of data such as "Peter"=>32
And, then, for each value, explode using '=>' as a separator, to split the name and the age
Removing the double-quotes arround the name, of course.
For example, you could use something like this :
$result = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(', ', $ages2) as $couple) {
list ($name, $age) = explode('=>', $couple);
$name = trim($name, '"');
$result[$name] = $age;
}
var_dump($result);
And, dumping the array, you'd get the following output :
array
'Peter' => string '32' (length=2)
'Quagmire' => string '30' (length=2)
'Joe' => string '34' (length=2)
Which means that using this :
echo $result['Peter'];
Would get you :
32
Of course it doesn't work. explode just splits by the given delimiter but doesn't create an associative array.
Your only hope if you really have such a string is to parse it manually. Either using preg_match_all, or I suppose you could do:
$array = eval('return array('.$ages2.');');
But of course this isn't recommended since it could go wrong in many many ways.
In any case I'm pretty sure you can refactor this code or give us more context if you need more help.
You'll need to build the array yourself by extracting the name and age:
<?php
$array = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(",", $ages2) as $element) {
$parts = explode("=>", $element);
if (count($parts) == 2) {
$name = str_replace(array('"', ' '), '', $parts[0]);
$age = (int) $parts[1];
$array[$name] = $age;
}
}
print_r($array);
$ages2 is not an array, so what you're trying here won't work directly, but you can transform a string with that structure into an array like this:
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$items = explode(",", $ages2);
foreach ($items as $item) {
list($key,$value) = explode('=>',$item);
$key = str_replace('"','',trim($key)); // Remove quotes and trim whitespace.
$array[$key] = (int)$value;
}
If you var_dump($array), you'll have:
array(3) {
["Peter"]=>
int(32)
["Quagmire"]=>
int(30)
["Joe"]=>
int(34)
}
So you can do this as expected and get 32 back out:
echo $array['Peter']

Exploding Arrays in PHP While Keeping the Original Key

How can I do the following without lots of complicated code?
Explode each value of an array in PHP (I sort of know how to do this step)
Discard the first part
Keep the original key for the second part (I know there will be only two parts)
By this, I mean the following:
$array[1]=blue,green
$array[2]=yellow,red
becomes
$array[1]=green //it exploded [1] into blue and green and discarded blue
$array[2]=red // it exploded [2] into yellow and red and discarded yellow
I just realized, could I do this with a for...each loop? If so, just reply yes. I can code it once I know where to start.
given this:
$array[1] = "blue,green";
$array[2] = "yellow,red";
Here's how to do it:
foreach ($array as $key => $value) {
$temp = explode(",", $value, 2); // makes sure there's only 2 parts
$array[$key] = $temp[1];
}
Another way you could do it would be like this:
foreach ($array as $key => $value) {
$array[$key] = preg_replace("/^.+?,$/", "", $value);
}
... or use a combination of substr() and strpos()
Try this:
$arr = explode(',','a,b,c');
unset($arr[0]);
Although, really, what you're asking doesn't make sense. If you know there are two parts, you probably want something closer to this:
list(,$what_i_want) = explode('|','A|B',2);
foreach ($array as $k => &$v) {
$v = (array) explode(',', $v);
$v = (!empty($v[1])) ? $v[1] : $v[0];
}
The array you start with:
$array[1] = "blue,green";
$array[2] = "yellow,red";
One way of coding it:
function reduction($values)
{
// Assumes the last part is what you want (regardless of how many you have.)
return array_pop(explode(",", $values));
}
$prime = array_map('reduction', $array);
Note: This creates a different array than $array.
Therefore $array == $prime but is not $array === $prime

Categories