Convert a string to an array in PHP - 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);

Related

Easy way to get comma seperate value from the array using PHP

I have this variable $sid and its output is below.
$sid = $_POST['sid'];
// sid consists values like this.
Array
(
[0] => 1
[1] => 2,3
)
now I need to run a query with this sid 1, 2 and 3. To do that I am using following code:
$ex = array();
foreach ( $sid as $key => $value) {
$ex[] = explode(',', $value);
}
foreach ($ex as $key => $value) {
foreach ($value as $k => $v) {
echo $v;
// my query where sid = $v
}
}
Is there any better way without multiple foreach loop?
Try this:
$ex = explode(',', implode(',', $sid));
foreach ($ex as $v) {
echo $v;
}
Basically, your input is an array of strings of comma-separated values, so, you can merge these strings into single string with comma as separator, and then split whole thing using single explode call.

Remove, add, move array indexes

I have a string that I converted to a multi-dimensional array.
String: 13,4,3|65,1,1|27,3,2
I wanna be able to move 27,3,2 to index 1 for example, so it would become:
13,4,3|27,3,2|65,1,1
Or remove one of those sections.
I know I can unset(), but I'm not sure how to search for an index then move it or unset it.
You can try the below one for interchanging the position of last two elements
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key] = $array[$key-1];
$array[$key-1] = $value;
}
}
This is for removing the second element.
$array = [0 => array(13,4,3), 1=>array(65,1,1), 2 => array(27,3,2)];
foreach($array as $key => $value) {
if($key == count($array)-1) {
$array[$key-1] = $value;
unset($array[$key]);
}
}
Loop through the array using foreach
foreach($array as $key => $value)
From key you can get the key and can do whatever you like.
Other wise, you can do this if you know the key
echo $array['pass_key_name_here'];

How to extract all 2nd level values (leaf nodes) from a 2-dimensional array and join with commas?

How can I get the list of values from my array:
[data] => Array
(
[5] => Array
(
[0] => 19
[1] => 18
[2] => 20
)
[6] => Array
(
[0] => 28
)
)
Expected output result string will be: 19,18,20,28
Thanks!
With one line, no loop.
echo implode(',', call_user_func_array('array_merge', $data));
Try it here.
Use following php code:
$temp = array();
foreach($data as $k=>$v){
if(is_array($v)){
foreach($v as $key=>$value){
$temp[] = $value;
}
}
}
echo implode(',',$temp);
Use following code.
$string = '';
foreach($yourarray as $k){
foreach($k as $l){
$string. = $l.",";
}
}
Just loop over sub arrays. Store values to $result array and then implode with ,
$result = array();
foreach ($data as $subArray) {
foreach ($subArray as $value) {
$result[] = $value;
}
}
echo implode(',', $result);
$data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
foreach ($array as $array1) {
echo $array1.'<br>';
}
}
Try this one. It will help you
Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});
Output:
19,18,20,28
This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)
I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array. It's a tidy little one-liner with a bit of regex magic. (Regex Demo) It effectively removes all square & curly brackets and double-quoted keys with trailing colons.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));
Output:
19,18,20,28
To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.
try with this..
foreach($data as $dataArr){
foreach ($subArray as $value) {
$res[] = $value;
}
}
echo implode(',', $res);
Just use nested foreach Statements
$values = array();
foreach($dataArray as $key => $subDataArray) {
foreach($subDataArray as $value) {
$values[] = $value;
}
}
$valueString = implode(',', $values);
Edit: Added full solution..

String to an array and then foreach

I have a variable string which is passed to an and array then foreach that just does not want to work. Below is the code im using.
$explode = $_obj->getModDependencies();
//this variable will returns/echos the string as #ModA,#Mod_b,#Mod3 etc (yes # is in each value)
and the foreach and array php code im using
$arr = array($explode);
foreach ($arr as $value) {
echo ''.$value.'';
}
if i use the above code it echos one hyperlink with each value at the end of it (http://myurl/mod?mod_id=#ModA,#Mod_b,#Mod3) but i want to echo each hyperlink for each value.
Which would be
http://myurl/mod?mod_id=#ModA
http://myurl/mod?mod_id=#Mod_b
and so forth.
But if i place the actual variable output string directly into the array it echos out how i want it (see below code that works)
$arr = array(#ModA,#Mod_b,#Mod3);
foreach ($arr as $value) {
echo ''.$value.'';
}
Any help wold be awesome!!
$arr = array($explode);
Thats the issue, just by saying something is within array() doesnt really make it an array as you expect it to be. You only gave it 1 argument.
You also mentioned the value of $explode is like this #ModA,#Mod_b,#Mod3. Just by naming something $explode doesn't explode it. You have to explode it yourself
$arr=explode(",","#ModA,#Mod_b,#Mod3");
//$arr=explode(",",$explode) in your case
Once that is done, your loop is already fine
foreach ($arr as $value) {
echo ''.$value.'';
}
Fiddle
When your variable $explode will be a string as '#ModA,#Mod_b,#Mod3' then you have to explode it.
$arr = explode(',', $explode);
foreach ($arr as $value) {
echo ''.$value.'';
}

how to explode the index of an array in PHP?

I have an array like
Array
(
[select_value_2_1] => 7
)
I want to explode index into Array ([0]=select_value, [1]=2, [2]=1)
Use array_keys to get your keys:
http://php.net/manual/en/function.array-keys.php
Or use a foreach loop:
foreach($elements as $key => $value){
print_r (explode("_", $key));
}
You can't just use explode() because it will also separate select from value. You could alter your output so that instead you have array keys like selectValue_2_1.
Then you can do what you want:
$items = array('selectValue_2_1' => 1);
foreach ($items as $key => $value) {
$parts = explode('_', $key);
}
That will yield, for example:
array('selectValue', '2', '1');
You can use array_keys() to extract the keys from an array.
Or if you want to split the keys as in your example, use a more complex function:
foreach ($array as $key=>$value) {
$key_parts = preg_split('/_(?=\d)/', $key);
}
If you always have the exact pattern, you could use a regular expression to extract the values:
foreach ($array as $key=>$value) {
if(preg_match('/(select_value)_(\d+)_(\d+)/', $key, $result)) {
array_shift($result); // remove full match
}
}
The performance of this may suck because you have a regular expression and an array operation.
<?php
$arr=array("select_value_2_1" => 7);
$keys= array_keys($arr);
$key=$keys[0];
$new_arr=explode("_",$key);
print_r($new_arr);
?>

Categories