This question already has answers here:
Imploding an associative array in PHP
(10 answers)
Closed 8 years ago.
I have a named array that look like this:
$arr = array('name'=>'somename','value'=>'somevalue');
I want to turn that array into something like this:
name='somename' value='somevalue'
I tried http_build_query() to do it.
echo http_build_query($arr, '', ' ');
But this is the result I get:
name=somename%21 value=somevalue%21
How can I get the result I want with http_build_query()? Or, is there any PHP function to do it?
Thank you.
http_build_query returns a urlencoded string. If you don't want that you can run it through urldecode
$arr = array('name'=>"'somename'",'value'=>"'somevalue'");
print urldecode(http_build_query($arr,null,' '));
Try with foreach()
$arr = array('name'=>'somename','value'=>'somevalue');
$str = '';
foreach($arr as $k=>$v) {
$str.= "$k='$v' ";
}
echo $str;
foreach ($array as $key => $value) {
$result .= "$key='$value' ";
}
echo rtrim($result,' ');
Related
This question already has answers here:
array_walk_recursive to apply function to each array element not working at all
(3 answers)
Closed 4 months ago.
I have a string in encoded array format. What I want is to replace the curly bracket in its value only. I have tried like this
$str = '[{"id":"{3e71209}","elType":"section","settings":[],"elements":[{"id":"70e5fb7","elType":"column","settings":{"_column_size":100,"_inline_size":null},"elements":[{"id":"70e09a1","elType":"widget","settings":{"title":"{title1|title2|title3}"},"elements":[],"widgetType":"heading"}],"isInner":false}],"isInner":false}]';
echo 'str asli: '.$str;
echo '<br><br>';
$strOlah = str_replace("{", "xx", json_decode($str));
echo 'str olah: '. json_encode($strOlah);
it's resulting the exact str. nothing change.
My expected result is the str become like this
[{"id":"xx3e71209}","elType":"section","settings":[],"elements":[{"id":"70e5fb7","elType":"column","settings":{"_column_size":100,"_inline_size":null},"elements":[{"id":"70e09a1","elType":"widget","settings":{"title":"xxtitle1|title2|title3}"},"elements":[],"widgetType":"heading"}],"isInner":false}],"isInner":false}]
How to do that without looping through an array because the structure and key of the array are very dynamic.
You need to loop through the array, calling str_replace() on the specific object properties.
$array = json_decode($str);
foreach ($array as $obj) {
$obj->id = str_replace("{", "xx", $obj->id);
foreach ($obj->elements as $el1) {
foreach ($el1->elements as $el2) {
$el2->settings->title = str_replace("{", "xx", $el2->settings->title);
}
}
}
echo 'str olah: ' . json_encode($array);
This question already has answers here:
Convert backslash-delimited string into an associative array
(4 answers)
Closed 6 years ago.
I have the following string which I've managed to get cleaned up into a clear format:
string(191) "twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0 "
I am now trying to take this and create an array so each digit is associated with its platform.
$shares = array(
'twitter' => 3,
'facebookshare_count' => 5,
'like_count' => 0
)
and so on...
I've been looking at the explode function, using spaces as the delimiter, but I'm really stuck on how to achieve this end result.
I am relatively new to PHP, and struggling to find the words to use to search for this problem. I don't know if 'array' or 'object' is even the right terminology here.
$str = 'twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0';
$strArray = explode(' ', $str);
$desiredArray = [];
foreach ($strArray as $value) {
$value = explode(":", $value);
$desiredArray[$value[0]] = $value[1];
}
$myString = "twitter:3 facebookshare_count:5 like_count:0 comment_count:0 total_count:8 click_count:5 buffer:0 pinterest:0 linkedin:0 stumbleupon:0 redditscore:0 ups:8 downs:3 google:4 delicious:0 digg:0";
$parseString = explode(" ", $myString);
$newArray = [];
foreach($parseString as $item) {
$splitItem = explode(":", $item);
$newArray[$splitItem[0]] = $splitItem[1];
}
foreach($newArray as $key=>$data) {
echo $key . " " . $data . "<br>";
}
Hope it helps !!!
This question already has answers here:
Finding the subsets of an array in PHP
(5 answers)
Closed 7 years ago.
I will do my best to explain this idea to you. I have an array of values, i would like to know if there is a way to create another array of combined values. So, for example:
If i have this code:
array('ec','mp','ba');
I would like to be able to output something like this:
'ec,mp', 'ec,ba', 'mp,ba', 'ec,mp,ba'
Is this possible? Ideally i don't want to have duplicate entries like 'ec,mp' and 'mp,ec' though, as they would be the same thing
You can take an arbitrary decision to always put the "lower" string first. Once you made this decision, it's just a straight-up nested loop:
$arr = array('ec','mp','ba');
$result = array();
foreach ($arr as $s1) {
foreach ($arr as $s2) {
if ($s1 < $s2) {
$result[] = array($s1, $s2);
}
}
}
You can do it as follows:
$arr = array('ec','mp','ba', 'ds', 'sd', 'ad');
$newArr = array();
foreach($arr as $key=>$val) {
if($key % 2 == 0) {
$newArr[] = $val;
} else {
$newArr[floor($key/2)] = $newArr[floor($key/2)] . ',' . $val;
}
}
print_r($newArr);
And the result is:
Array
(
[0] => ec,mp
[1] => ba,ds
[2] => sd,ad
)
Have you looked at the function implode
<?php
$array = array('ec','mp','ba');
$comma_separated = implode(",", $array);
echo $comma_separated; // ec,mp,ba
?>
You could use this as a base for your program and what you are trying to achieve.
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Ok, I know that to get a comma-seperated string from a string array in PHP you could do
$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);
But what if I have an array of arrays(not a simple string array)?
$myAssociativeA =
array(
[0] => array("type"=>"cat", "sex"=>"male")
, [1] => array("type"=>"dog", "sex"=>"male")
);
and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried
$myGoal = join(',', $myAssociativeA{'type'});
My target value for $myGoal in this case would be "cat,dog".
Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?
This should work for you:
(Here I just get the column which you want with array_column() and simply implode it with implode())
echo implode(",", array_column($myAssociativeA, "type"));
Another option is to use array_walk() to return the key you want:
array_walk($myAssociativeA, function(&$value, $key, $return) {
$value = $value[$return];
}, 'type');
echo implode(', ', $myAssociativeA); // cat, dog
Useful for older PHP versions - #Rizier123's answer using array_column() is great for PHP 5.5.0+
You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to #Rizier123) and you can't use array_column()
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));
echo $myGoal;
?>
EDIT: with the recommendation in the comment of #scrowler the code now is:
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';
$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));
echo $myGoal;
?>
Output:
cat,dog
Read more about array_map in:
http://php.net/manual/en/function.array-map.php
You just have to loop over the array and generate the string yourself.
<?php
$prepend = '';
$out = '';
$myAssociativeA = array(
array('type' => 'cat'),
array('type' => 'dog')
);
foreach($myAssociativeA as $item) {
$out .= $prepend.$item['type'];
$prepend = ', ';
}
echo $out;
?>
You could easily turn this into a function.
<?php
function implode_child($array,$key) {
$prepend = '';
$out = '';
foreach($array as $item) {
$out .= $prepend.$item[$key];
$prepend = ', ';
}
return $out;
}
?>
Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.
$csvString = "";
foreach ( $myAssociativeA as $row ) {
$csvRow = implode(",", $row);
$csvString .= $csvRow . PHP_EOL;
}
Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.
This question already has answers here:
Parse query string into an array
(12 answers)
Closed 8 months ago.
I have a string like this:
"birs_appointment_price=&birs_appointment_duration=&birs_appointment_alternative_staff=&birs_shortcode_page_url=http%3A%2F%2Flocalhost%2Fstreamline-new%2Fworkshop%2F&_wpnonce=855cbbdefa&_wp_http_referer=%2Fstreamline-new%2Fworkshop%2F&birs_appointment_location=17858&birs_appointment_staff=-1&birs_appointment_avaliable_staff=-1%2C17859&birs_appointment_service=-1&birs_appointment_date=&birs_appointment_notes=&birs_appointment_fields%5B%5D=_birs_appointment_notes&birs_client_type=new&birs_client_name_first=&birs_client_fields%5B%5D=_birs_client_name_first&birs_client_name_last=&birs_client_fields%5B%5D=_birs_client_name_last&birs_client_email=&birs_client_fields%5B%5D=_birs_client_email&birs_field_1=&birs_client_fields%5B%5D=_birs_field_1&birs_client_fields%5B%5D=_birs_field_6&s="
I want to parse it to array in php. How to do it ?. Thanks for your help so much.
You use parse_str for this. (http://php.net/manual/en/function.parse-str.php)
$output = array();
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
Or you can parse it into local variables
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
You can try the following :
inside this foreach you will get all the get parameters and then you can store them in an array.
foreach($_GET as $key => $value) {
//your code here
}
use
parse_str( $string );
Refer: http://php.net/manual/en/function.parse-str.php
$your_str = 'birs_appointment_price=&birs_appointment_duration=&birs_appointment_alternative_staff=&birs_shortcode_page_url=http%3A%2F%2Flocalhost%2Fstreamline-new%2Fworkshop%2F&_wpnonce=855cbbdefa&_wp_http_referer=%2Fstreamline-new%2Fworkshop%2F&birs_appointment_location=17858&birs_appointment_staff=-1&birs_appointment_avaliable_staff=-1%2C17859&birs_appointment_service=-1&birs_appointment_date=&birs_appointment_notes=&birs_appointment_fields%5B%5D=_birs_appointment_notes&birs_client_type=new&birs_client_name_first=&birs_client_fields%5B%5D=_birs_client_name_first&birs_client_name_last=&birs_client_fields%5B%5D=_birs_client_name_last&birs_client_email=&birs_client_fields%5B%5D=_birs_client_email&birs_field_1=&birs_client_fields%5B%5D=_birs_field_1&birs_client_fields%5B%5D=_birs_field_6&s=';
$_VARS = array();
parse_str($your_str, $_VARS);
echo $_VARS['birs_appointment_price'];