how to get associative array from string - php

I have one string like:-
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
Now, I want to get it in following associative array format:-
$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}
Note:- These all values are separated by space only. Any help will be appreciable.
Thanks in advance

$final_array = array();
$kvps = explode(' ', $attributes);
foreach( $kvps as $kvp ) {
list($k, $v) = explode('=', $kvp);
$final_array[$k] = $v;
}

I can suggest you to do it with a regular expression:
$str = "id=1 username=puneet mobile=0987778987 u_id=232";
$matches = array();
preg_match_all( '/(?P<key>\w+)\=(?P<val>[^\s]+)/', $str, $matches );
$res = array_combine( $matches['key'], $matches['val'] );
working example in phpfiddle

$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
$temp2 = explode("=", $v);
$attributes[$temp2[0]] = $temp2[1];
}
EXPLODE

this code will solve your problem.
<?php
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
$a = explode ( ' ', $attributes) ;
$new_array = array();
foreach($a as $value)
{
//echo $value;
$pos = strrpos($value, "=");
$key = substr($value, 0, $pos);
$value = substr($value, $pos+1);
$new_array[$key] = $value;
}
print_r($new_array);
?>
out put of this code is
Array ( [id] => 1 [username] => puneet [mobile] => 0987778987 [u_id] => 232 )

I think you have to split this string two times
divide with space
divide with '='

Related

Remove a part of string from each element of an array in php

I have a array
["item1","item2","item3"]
I want to get an array of ["1","2","3"]
how to get that in php
You need this
$arr = ["item1","item2","item3"];
for ($i = 0; $i < sizeof($arr); $i++) {
// replace "item" with ""
$arr[$i] = str_replace("item","",$arr[$i]);
}
<?php
$given_array = ["item1","item2","item3"];
$new_array = array();
foreach ($given_array as $arr) {
$new_array[] = intval(preg_replace('/[^0-9]+/', '', $arr), 10);
}
echo '<pre>';
print_r($new_array);
?>
1) Simply use
$res = str_replace('item', '', $array);
Output
$res
Array
(
[0] => 1
[1] => 2
[2] => 3
)
2) Using array_map()
$array = array_map(
function($str) {
return str_replace('item', '', $str);
},
$array
);

Extract numbers separated by special char from string

If I have a string like:
123*23*6594*2*-10*12
How can I extract the single numbers, in the string separated by *? That is, I want this output:
a=123, b=23, c=6594, d=2, e=-10, f=12.
Flexible:
$vars = range('a', 'z');
$vals = explode('*', $string);
$result = array_combine(array_slice($vars, 0, count($vals)), $vals);
Result:
Array
(
[a] => 123
[b] => 23
[c] => 6594
[d] => 2
[e] => -10
[f] => 12
)
Just for the sheer fun of setting the result as an iterable (rather than an actual array) with the alpha keys in a slightly different manner:
$data = '123*23*6594*2*-10*12';
function dataseries($data) {
$key = 'a';
while (($x = strpos($data, '*')) !== false) {
yield $key++ => substr($data, 0, $x);
$data = substr($data, ++$x);
}
yield $key++ => $data;
}
foreach(dataseries($data) as $key => $value) {
echo $key, ' = ', $value, PHP_EOL;
}
Requires PHP >= 5.5.0
You can use simple as this :
$str = "123*23*6594*2*-10*12";
$arr = explode("*",$str);
$arr['a']=$arr[0];
$arr['b']=$arr[1];
$arr['c']=$arr[2];
$arr['d']=$arr[3];
$arr['e']=$arr[4];
$arr['f']=$arr[5];
echo "a=" .$arr['a'] ." b=". $arr['b']." c=". $arr['c']." d=". $arr['d']." e=". $arr['e']." f=". $arr['f'];
EDIT:
To accomplish Rizier123 wish :
$str = "123*23*6594*2*-10*12";
$arr = explode("*",$str);
$vars = range('a', 'z');
foreach ($arr as $val => $key){
echo $vars[$val]."=".$key."<br>";
}
something like:
list($a,$b,$c,$d,$e,$f) = explode("*", $str);
Just a guess ;)

Split a string into keys of associative arrays (PHP)

Do you have an idea, how can a string be converted to a variable, e.g.
there is a string -> $string = 'one|two|three';
there is an array -> $arr = array('one' => array('two' => array('three' => 'WELCOME')));
I want to use all with explode(); exploded values to access the array $arr. I tried this code:
$c = explode('|', $string);
$str = 'arr[' . implode('][', $c) . ']';
echo $$str;
It doesnt work, sadly :( Any ideas?
You're doing it wrong.
You can do what you want with a loop to go through the array level by level
$string = 'one|two|three';
$arr = array('one' => array('two' => array('three' => 'WELCOME')));
$c = explode('|', $string);
$result = $arr;
foreach($c as $key)
$result = $result[$key];
echo $result; // WELCOME
Here's a sort of recursive function:
$ex_keys = array('one', 'two', 'three');
$ex_arr = array('one' => array('two' => array('three' => 'WELCOME')));
function get_recursive_var($keys, $arr) {
if (sizeof($keys) == 1)
return $arr[$keys[0]];
else {
$key = array_shift($keys);
return get_recursive_var($keys, $arr[$key]);
}
}
var_dump(get_recursive_var($ex_keys, $ex_arr));

combine array php

In my output code is as:
Array (
[0] => 53,67,70
[1] => 48
[2] => 11,22,13
);
I want in output as: array(11,22,13,48,53,67,70)
$result = $this->db->get_where('table',array('mainpage'=>$mp'));
$data = array();
$out = array();
foreach($result->result() as $row){
$dv = json_decode($row->subpage);
$out = array_merge($dv, $out);
}
return $out;
In my database table rows are as: (json data)
Row 1 : ["11,22,13"]
Row 2 : ["48"]
Row 3 : ["53,67,70"]
How must fixed php code for output as array(11,22,13,48,53,67,70) ?
$result = $this->db->get_where('table',array('mainpage'=>$mp));
$data = array();
$out = array();
foreach($result->result() as $row){
$dv = json_decode($row->subpage);
$flat = array();
foreach ( $dv as $item ) {
$flat = array_merge( $flat, explode( ',', $item ) );
}
$out = array_merge( $out, $flat );
}
return $out;
$array = array (array (53, 67, 70), array (48), array (11, 22, 13));
$combined_array = call_user_func_array ('array_merge', $array);

PHP array manipulation

I have an array as $arr = array("name" => "Fom Xong" , "Sales" => "100");
From this array I want to generate a string something like this
$str = 'name="Fom Xon" Sales="100"';
Is it possible???
thanks in advance
For example you can do like this:
$tmp_arr = array();
foreach ($arr as $key => $val)
$tmp_arr[] = $key.'="'.$val.'"';
$str = implode(' ', $tmp_arr);
$output = array();
foreach ($arr as $key => $value) {
$output[] = "$key=\"$value\"";
}
echo join(' ', $output);
Or:
echo join(' ', array_map(function ($key, $value) { return "$key=\"$value\""; }, array_keys($arr), $arr));

Categories