How implode correctly this array? - php

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

Related

Explode a string into bidimensional array

Excuse me if this question was already solved. I've searched trough the site and couldn't find an answer.
I'm trying to build a bi-dimensional array from a string. The string has this structure:
$workers="name1:age1/name2:age2/name3:age3"
The idea is to explode the array into "persons" using "/" as separator, and then using ":" to explode each "person" into an array that would contain "name" and "age".
I know the basics about the explode function:
$array=explode("separator","$string");
But I have no idea how to face this to make it bidimensional. Any help would be appreciated.
Something like the following should work. The goal is to first split the data into smaller chunks, and then step through each chunk and further subdivide it as needed.
$row = 0;
foreach (explode("/", $workers) as $substring) {
$col = 0;
foreach (explode(":", $substring) as $value) {
$array[$row][$col] = $value;
$col++;
}
$row++;
}
$array = array();
$workers = explode('/', "name1:age1/name2:age2/name3:age3");
foreach ($workers as $worker) {
$worker = explode(':', $worker);
$array[$worker[0]] = $worker[1];
}
Try this code:
<?php
$new_arr=array();
$workers="name1:age1/name2:age2/name3:age3";
$arr=explode('/',$workers);
foreach($arr as $value){
$new_arr[]=explode(':',$value);
}
?>
The quick solution is
$results = [];
$data = explode("/", $workers);
foreach ($data as $row) {
$line = explode(":", $row);
$results[] = [$line[0], $line[1]];
}
You could also use array_walk with a custom function which does the second level split for you.
This is another approach, not multidimensional:
parse_str(str_replace(array(':','/'), array('=','&'), $workers), $array);
print_r($array);
Shorter in PHP >= 5.4.0:
parse_str(str_replace([':','/'], ['=','&'], $workers), $array);
print_r($array);
yet another approach, since you didn't really give an example of what you mean by "bidimensional" ...
$workers="name1:age1/name2:age2/name3:age3";
parse_str(rtrim(preg_replace('~name(\d+):([^/]+)/?~','name[$1]=$2&',$workers),'&'),$names);
output:
Array
(
[name] => Array
(
[1] => age1
[2] => age2
[3] => age3
)
)

Convert a string to an array in PHP

I have an array like such:
array('some_key' => 'some_value');
I would like to take that and transform it to, this should be done programatically
array('some_key' => array('some_value'));
This should be rather simple to do but the only think I can find is answers on string split and explode, to explode strings into arrays. I thought PHP, like other languages, had something called to_array or toArray.
I am assuming this is super easy to do?
If you're just doing the one array element, it's as simple as:
$newarray['some_key'] = array($sourcearray['some_key']);
Otherwise if your source array will have multiple entries, you can do it in a loop:
foreach($sourcearray AS $key => $value) {
$newarray[$key] = array($value);
}
Something as simple as $value = array($value) should work:
foreach ($array as &$value) {
$value = array($value);
}
unset($value); //Remove the reference to the array value
If you prefer to do it without references:
foreach ($array as $key => $value) {
$array[$key] = array($value);
}
You can try like this
<?php
$arr=array('some_key' => 'some_value');
foreach($arr as $k=>$v)
{
$newarr[$k] = array($v);
}
var_dump($newarr);

how to change illegal characters in php extract function?

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);
?>

How to handle my data?

Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_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.

Categories