when i load a database single data,it's seems like array,
but i don't know how to get the value in label_values
print_r($results):
Array ( [custom_params] => custom_limit="0"|input_label="{\"label_values\":[\"\u9650\u5916\u5e36\",\"\u9650\u5167\u7528\",\"\u9650\u6642\u5546\u54c1\",\"\u514d\u9810\u7d04\",\"\u5373\u8cb7\u5373\u7528\",\"\u672c\u9031\u5f37\u6a94\",\"\u611b\u5fc3\u516c\u76ca\"]}"|repeat_label=""| )
json_encode($results):
{"custom_params":"custom_limit=\"0\"|input_label=\"{\\\"label_values\\\":[\\\"\\u9650\\u5916\\u5e36\\\",\\\"\\u9650\\u5167\\u7528\\\",\\\"\\u9650\\u6642\\u5546\\u54c1\\\",\\\"\\u514d\\u9810\\u7d04\\\",\\\"\\u5373\\u8cb7\\u5373\\u7528\\\",\\\"\\u672c\\u9031\\u5f37\\u6a94\\\",\\\"\\u611b\\u5fc3\\u516c\\u76ca\\\"]}\"|repeat_label=\"\"|"}
tried foreach first lavel:
foreach($results as $k=>$v){
echo $v;
}
get:
custom_limit="0"|input_label="{\"label_values\":[\"\u9650\u5916\u5e36\",\"\u9650\u5167\u7528\",\"\u9650\u6642\u5546\u54c1\",\"\u514d\u9810\u7d04\",\"\u5373\u8cb7\u5373\u7528\",\"\u672c\u9031\u5f37\u6a94\",\"\u611b\u5fc3\u516c\u76ca\"]}"|repeat_label=""|
but don't know to get value then...
Any help is greatly appreciated!
$results['custom_params'] is a pipe-delimited list of key=value pairs, so you need to split it up. And the input_label value there is JSON, which you can parse with json_decode.
Also, you need to remove the backslashes before the quotes in the value.
$custom_params = explode('|', $results['custom_params']);
foreach ($custom_params as $param) {
if (preg_match('/^input_label="(.*)"$/', $param, $match)) {
$input_label = json_decode(str_replace('\"', '"', $match[1]), true);
$label_values = $input_label['label_values'];
break;
}
}
DEMO
Related
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));
I am trying to parse a csv file to insert the csv contents into my Database. After the data is parsed the array looks like
Array
(
[AirportCode
] => GKA
)
and i would like to extract the AirportCode GKA and insert it. Everything looks fine but the key and Value in the above array having line breaks.
Sample code:
foreach($data['csvData'] as $field)
{
print_r($field);
$AirportCode = str_replace(PHP_EOL, '', $field['AirportCode']);
echo $AirportCode ;
}
But the AirportCode is always returning empty. I just want to get-rid of those line breaks. Can someone help me...?
Untested
I'm not sure about str_replace() capabilities on recognizing newline characters by using the escape reference, but it's worth a shot.
However your airport code is returning nothing, because the actual key seems to have a \n (new line character) in.
function fixArrayKey(&$arr)
{
$arr=array_combine(array_map(function($str){
return str_replace("\n ","",$str);
},array_keys($arr)),array_values($arr));
foreach($arr as $key=>$val)
{
if(is_array($val)) fixArrayKey($arr[$key]);
}
}
For your array values however you could just use:
function fixArrayValue($arr)
{
$return = array();
foreach($arr AS $key => $value){
$return[$key] = rtrim($value, "\n");
}
return $return
}
there is no array key called 'AirportCode' the actual key has a line break in it.
I would create a clean array by looping through the key value pairs, and adding them to a new array:
$clean=array();
foreach($data['csvData'] as $key => $value){
$ckey = str_replace(array("\r", "\n"), '', $key);
$cvalue = str_replace(array("\r", "\n"), '', $value);
$clean[$ckey]=$cvalue;
}
var_dump($clean);
I have a page with a form where I post all my checkboxes into one array in my database.
The values in my database looks like this: "0,12,0,15,58,0,16".
Now I'm listing these numbers and everything works fine, but I don't want the zero values to be listed on my page, how am I able to search through the array and NOT list the zero values ?
I'm exploding the array and using a for each loop to display the values at the moment.
The proper thing to do is to insert a WHERE statement into your database query:
SELECT * FROM table WHERE value != 0
However, if you are limited to PHP just use the below code :)
foreach($values AS $key => $value) {
//Skip the value if it is 0
if($value == 0) {
continue;
}
//do something with the other values
}
In order to clean an array of elements, you can use the array_filter method.
In order to clean up of zeros, you should do the following:
function is_non_zero($value)
{
return $value != 0;
}
$filtered_data = array_filter($data, 'is_non_zero');
This way if you need to iterate multiple times the array, the zeros will already be deleted from them.
you can use array_filter for this. You can also specify a callback function in this function if you want to remove items on custom criteria.
Maybe try:
$out = array_filter(explode(',', $string), function ($v) { return ($v != 0); });
There are a LOT of ways to do this, as is obvious from the answers above.
While this is not the best method, the logic of this might be easier for phpnewbies to understand than some of the above methods. This method could also be used if you need to keep your original values for use in a later process.
$nums = '0,12,0,15,58,0,16';
$list = explode(',',$nums);
$newList = array();
foreach ($list as $key => $value) {
//
// if value does not equal zero
//
if ( $value != '0' ) {
//
// add to newList array
//
$newList[] = $value;
}
}
echo '<pre>';
print_r( $newList );
echo '</pre>';
However, my vote for the best answer goes to #Lumbendil above.
$String = '0,12,0,15,58,0,16';
$String = str_replace('0', '',$String); // Remove 0 values
$Array = explode(',', $String);
foreach ($Array AS $Values) {
echo $Values."<br>";
}
Explained:
You have your checkbox, lets say the values have been converted into a string. using str_replace we have removed all 0 values from your string. We have then created an array by using explode, and using the foreach loop. We are echoing out all the values of th array minux the 0 values.
Oneliner:
$string = '0,12,0,15,58,0,16';
echo preg_replace(array('/^0,|,0,|,0$/', '/^,|,$/'), array(',', ''), $string); // output 12,15,58,16
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);
}
}
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.