I have a JSON string in this variable:
$value = $request->pre_departure_type;
With the value:
"30":0 ,"31":2
I want to get the values 30 and 0, 31 and 2 from the above JSON string.
I tried this code:
$result = array();
foreach (explode(',', $value) as $sub) {
$subAry = explode(':', $sub);
$result[$subAry[0]] = $subAry[1];
}
But this didn't explode the string on the double quotes.
If You are getting the perfect answer from your code then i think there is a problem because of double inverted comma. firstly remove it.
$str = str_replace('"', '', $value);
You will get value like below
value = 30:0 ,31:2
after that you will convert it in to array.
First replace double quotes and then do the same process as you did.
$result = array();
$newvalue = str_replace('"', '', $value);
foreach (explode(',', $value) as $sub) {
$subAry = explode(':', $sub);
$result[$subAry[0]] = $subAry[1];
}
If you are getting your desired result but with quotations then simply use this function to remove quotations:
$str = str_replace('"', '', $string_to_replace);
your value coming as a json format so first you need to convert it to object and then array and do manipulation as follow
$valueArr=(array)json_decode($value);
$finalArray=array();
foreach($valueArr as $k=>$v){
array_push($finalArray,$k);
array_push($finalArray,$v);
}
echo "<pre>";print_r($finalArray);
$value = '{"30":0 ,"31":2}'; // this is a json
$data = json_decode($value); // json to object
foreach($data as $key=>$value)
{
echo $key; // get key
echo $value; //get value
}
get values 30 and 0 , 31 and 2 from above
Related
I have a variable storing value separated by comma
$integers = 1,5,8,4,3;
I need To make every value like
$finalvalue = '1','5','8','4','3'
<?php
$integers = '1,5,8,4,3'; //Convert into String
$arr = explode(',', $integers); // String to Array Conversation
foreach ($arr as $key => $value) {
$val[] = "'".$value."'"; // add your requirements here
}
$finalvalue = implode(',', $val); // Array to string
echo $finalvalue; // your final result
?>
I need to sum all values of "initialContractualPrice" in http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate).
I ned to do the operations in php.
who know that can help me?
thank you very much ;)
Try
$data = file_get_contents('http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)');
$data = json_decode($data);
foreach($data as $dat){
echo $dat->publicationDate;
}
You can also use print_r or var_dump to see the structure
This should take care of it.
// Get json from url
$url = 'http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)';
$content = file_get_contents($url);
// Decode json into an array
$json = json_decode($content, true);
// Set default
$total = 0;
// Loop through the array created when decoding json
foreach ($json as $key)
{
// remove symbol from the end leaving only digits
$value = substr(utf8_decode($key['initialContractualPrice']), 0, -1);
// remove the decimal point
$value = str_replace('.', '', $value);
// replace the comma with a decimal point
$value = str_replace(',', '.', $value);
// add this number to the total value
$total += $value;
}
echo $total;
I have this options array:
string(111) "colors:black;white;transparent;pink;"
how can I explode it so I get as a label first separator : and the rest in array as options? I have this so far:
$options= explode(";",$rows[0]);
$htm= '<ul class="product_opts">'.$lang['available_options'].'';
foreach ($options as $value) {
$row=mysql_fetch_row($result);
$htm.='<li style="text-align:left;font-weight:normal;">'.$value.'</li>';
}
$htm.= '</ul>';
}
echo $htm;
but it returns the label as option too..
$attributes="colors:black;white;transparent;pink;";
list($attribute, $values) = array_map(
function($value) {
return array_filter(explode(';', $value));
},
explode(':', $attributes)
);
var_dump($attribute);
var_dump($values);
$str = "colors:black;white;transparent;pink;";
list($label, $optionsStr) = explode(":", $str);
$optionsStr = rtrim($optionsStr, ";");
$options = explode(";", $optionsStr);
echo "<pre>";
print_r($label);
print_r($options);
Explode string by :. First token will be your label, second token your options.
Explode second token by ;, and you have your options in an array.
Try
$str = "colors:black;white;transparent;pink;";
$arr = explode(";",$str);
$key = explode(":",$arr[0]);
$arr[0] = $key[1];
unset($arr[sizeof($arr)-1]);
See demo here
use split to do like so
$options= split("[;|:]",$rows[0]);
I have an array it contains key and value. i would like to converting into a string.
array(
[business_type]=>'cafe'
[business_type_plural] => 'cafes'
[sample_tag]=>'couch'
[business_name]=>'couch cafe'
)
Expected Output:
business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe
NOTE:
I was searching in StackOverflow and found the below question and it has answer. I want exactly reverse one.
converting string containing keys and values into array
Try
$data = array();
foreach($arr as $key=>$value) {
$data[] = $key.','.$value;
}
echo implode('|',$data);
Another Solution:
function test_alter(&$item1, $key, $delimiter)
{
$item1 = "$key".$delimiter."$item1";
}
array_walk($arr, 'test_alter',',');
echo implode('|',$arr);
Use the foreach() function to go through the array and string the keys/values together...
Assuming your array is called $array
$result = "";
foreach($array as $key => $value){
$result .= $key . "," . $value . "|";
}
It's as simple as that.
EDIT - Thanks Nelson
After that, lost the last |
$result = rtrim($result, "|");
try this
$pieces=array();
foreach(array('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3') as $k=>$v)
{
$pieces[]=$k.','.$v;
}
echo implode('|', $pieces);
I have a string I would like to separate and make a multidimensional array out of. The string looks like this:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
Unfortunately, I have no control over how the string is put together, which is why I'm trying to make this array.
My goal is to make an array like this:
$item[1]['color'] // = blue
$item[2]['material'] // = silk
So, here's what I've done:
$item = array();
$i=0; // I know this is messy
$eachitem = explode("item-",$string);
array_shift($eachitem); // get rid of the first empty item
foreach ($eachitem as $values) {
$i++; // Again, very messy
$eachvalue = explode(",",$values);
array_pop($eachvalue); // get rid of the last comma before each new item
foreach ($eachvalue as $key => $value) {
$item[$i][$key] = $value;
}
}
I'm obviously lost with this... any suggestions?
You're mostly there. Just replace your inner foreach with
foreach ($eachvalue as $value) {
$properties = explode(':', $value);
$item[$i][$properties[0]] = $properties[1];
}
You're close, this is how I would do it:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$substr = explode("item-", $string);
$items = array();
foreach ($substr as $string) {
$subitems = array();
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair, 2);
$subitems[$key] = $value;
}
$items[] = $subitems;
}
var_dump($items);
Using list here is great :) Do note that you would need the extra count limiter in explode else you might lose data if there are more :.
$array = array();
$string = explode(',', $string);
foreach($string as $part):
$part = trim($part);
if(strlen($part) < 3) continue;
$part = explode(':', $part);
$array[$part[0]] = $part[1];
endforeach;
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$num_attr = 3;
$item = array();
$i=$x=0;
foreach(explode(',', trim($string,',')) as $attr)
{
list($key, $value) = explode(':', $attr);
$item[$x+=($i%$num_attr==0?1:0)][$key] = $value;
$i++;
}
Set the $num_attr to the number of item attributes in the string (this will allow adjustments in the future if they grow/shrink). The trim inside the foreach is removing ay "empty" data like the last comma (it will also remove a empty first comma if one ever shows up). The crazy looking $item[$x+=($i%$num_attr==0?1:0)] is taking the modulus of the counter / number of attributes which when it is 0 that means we are on a new product line so we add 1 to x which populates the item number index, if the modulus returns a number then we know we are on the same product so we add 0 which doesn't change the items index so that attribute is added on to the same item.