Convert a string structured as a Multidimensional Array to array - php

I have this string:
array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));
Stored in $_POST['data']
The string Im receiving is via.load` function where the structure of the string is constructed like so.
I would like to convert it to a multidimensional array via php so I can loop through it easily
So far I`ve reached a workaround by modifying both the string and the method.
Now my string looks like this :
1,name1,1,0,|2,name2,0,1,|3,name3,0,1,|4,name4,1,1,|5,name5,1,0,|
And the method is this
$data2 = $_POST['data2']; /// get data
$data2 = substr_replace($data2 ,"", -2); // eliminate ,|
$data2 = $data2."|"; // add |
$one=explode("|",$data2); // create multidimensional array
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
I can keep this solution but I would like to know if there is another way of doing it as first requested

There is a better and simple way. You just need to use a foreach loop inside foreach loop.
$data = array(
array('1','name1','1','0'),
array('2','name2','0','1'),
array('3','name3','0','1'),
array('4','name4','1','1'),
array('5','name5','1','0')
);
foreach( $data as $d ) {
foreach( $d as $value ) {
echo $value;
echo '<br />';
}
}
You can check the online Demo

To parse your original string you can use eval()
$string = 'array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));';
eval('$array = '.$string);
But eval can/should be disabled on the server, because it comes with security issues.
What i would do is to use JSON, where you would POST the json encoding it with:
json_ecnode( $my_array );
and then decoding it:
$array = json_decode( $_POST['data'], true );

Related

How to convert comma separated key value string to associative array in PHP

I tried searching for a quick fix to converting a comma separated key=>value string to an associative array but couldn't find any. So i had to make a quick fix myself.
ANTECEDENT
I generated an array of some form elements using Jquery, to be sent via ajax.
So I have something like:
var myarray = [];
var string1 = 'key1=>'+form['value1'].value; //and we have string2 and more
myarray.push(string1);
Then i sent "myarray" as data to the form handling script.
PROBLEM
Now i have an array to deal with in my php script. I have the following:
function($var,$data){
$string = $data('myarray'); //array created earlier with jquery
}
Which is the same as:
...
$string = array(0=>'key1=>value1',1=>'key2=>value2');
...
Meanwhle, what i need is:
...
$string = array('key1'=>'value1','key2'=>'value2');
...
SOLUTION
...
$string = $data('myarray');
$string1 = array();
foreach($string as $value){
$split = explode('=>',$value);
$string1[$split[0]]=$split[1];
}
...
Now i can access the value of each key as:
echo $string1['key1']; //gives value1
This solution can also be used in a situation where you have:
$string = 'key1=>value1,key2=>value2...';
$string = explode(',',$string); // same as $string = array('key1'=>'value1',...)
$string1 = array();
foreach($string as $value){
$split = explode('=>',$value);
$string1[$split[0]]=$split[1];
}
The solution is rather simpler than i expected but if you know a better way to make this kind of conversion, feel free to suggest.
You can add as key value pair in javascript. Then you don't need to do any operations, can access directly in PHP.
var myarray = {};
myarray['key1'] = form['value1'].value;
In PHP :
$arr = $data('myarray');
echo $arr['key1']
Use explode() to split up the string.
$string = 'key1=>value1,key2=>value2,key3=>value3';
$pairs = explode(',', $string);
$data = array();
foreach ($pairs as $pair) {
list($key, $value) = explode('=>', $pair);
$data[$key] = $value;
}
var_dump($data);
DEMO

PHP changing array format

I'm trying to change an array format from this
{"updated":"2016-01-28 02:00:02","rate":"0.1898"}
to this
[2016-01-28 02:00 , 0.1898]
I'm getting the first array format from a MySQL query and need to convert to the second format to use in a line chart.
$newVal = array();
foreach ($dbresult as $key => $value) {
$newVal[] = json_encode(array_values($value));
}
echo implode(",", $newVal);
With this new code block i get this format
["2016-01-28 02:00" , "0.1898"]
But still need to get rid of the double quotes, any ideas?
$json = '[{"updated":"2016-01-28 02:00:02","rate":"0.1898"}]';
echo json_encode(array_map(function ($data) {
return [$data->updated, $data->rate];
}, json_decode($json)));
In other words:
JSON-decode it
loop through it
create a new array with updated in the first index and rate in the second
JSON-encode it again
Step 3 is necessary since JSON objects don't guarantee any particular order, so relying on the decoded order of the keys is not reliable; and it also guarantees you get the data you want even if you add more keys to your objects.
Try this code
$string = ' {"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$array = json_decode($string, true);
$str = json_encode(array_values($array));
echo str_replace('"', '', $str);
you should try this
$str ='{"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$data=json_decode($str);
echo '<pre>';
echo 'json decode it returns ojbects<br>';
print_r($data);
echo 'convert object into array<br>';
$data=(array)$data;
print_r($data);
echo 'Your Output<br>';
echo json_encode(array_values($data));

How to separate JSON Array with space in PHP

I have a JSONArray as
{"test":
[
{"Name":"aaa","Reg/Admission Number":"001"},
{...}]}
And I can separate Name by
$read_data = array();
foreach ($data->test as $result){
$name = $result->Name;
$read_data[] = "('$name')";
}
the result of read_data as ('aaa'),('bbb')...
Anyone can suggest how to separate the array of Reg/Admission Number which has the special character as '/' and 'space'
Why Dont you use the php function
json_encode() http://php.net/manual/en/function.json-encode.php
json_decode() http://php.net/manual/en/function.json-decode.php
As per #haxxxton suggestion it works
$read_data = array();
foreach ($data->test as $result){
$name = $result->Name;
$no = $result->{'Reg/Admission Number'}`
$read_data[] = "('$name','$no')";
}
You can convert json array to PHP array first and then can do your operation.

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.

Array a string in the following format?

How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:
101=1&2020=2&303=3
(Incase your wondering, its the result of jQuery Sortable Serialize...
I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?
I just want to explode this in a way that $key = 101 and $value = 1
Sounds confusing ;)
Thanks so so much in advanced!!
See the parse_str function.
It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:
$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);
One quick and dirty solution:
<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
list($key, $value) = each(explode('=', $pair));
$VAR[$key] = $value;
}
?>
parse_str($query_string, $array_to_hold_values);
$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
$pair = explode("=",$e);
$output[$pair[0]] = $pair[1];
}
Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.

Categories