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);
Related
I have below small PHP script, I just need the value from the array if I provide key in $str.
$empid_array = array('CIP004 - Rinku Yadav', 'CIP005 - Shubham Sehgal');
$key = array();
$value = array();
$str = "CIP004";
foreach($empid_array as $code){
$str = preg_split("/\-/", $code);
array_push($key, $str[0]);
array_push($value, $str[1]);
}
$combined = array_combine($key, $value);
echo count($combined);
foreach($combined as $k => $v){
if($str == $k){
echo $v;
}
}
You could simplify your code considerably here. Step one, use array_walk to walk through the array and build the $combined array. Step two, there's no point in looping through the array, just access the value by the index:
$empid_array = ['CIP004 - Rinku Yadav', 'CIP005 - Shubham Sehgal'];
$str = "CIP004";
$combined = [];
// passing $combined by reference so we can modify it
array_walk($empid_array, function ($e) use (&$combined) {
list($id, $name) = explode(" - ", $e);
$combined[$id] = $name;
});
echo $combined[$str] ?? "Not found";
I have an input string that has the following value:
"[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"
I want to convert this into a php array that looks something like this:
$date=2018-05-08;
$meal=1;
$option=17;
can someone help me please !
<?php
$data="[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$data=explode(',',$data);
foreach($data as $row){
preg_match_all('#\[(.*?)\]#', $row, $match);
$date=$match[1][0];
$meal=$match[1][1];
$option=$match[1][2];
}
This will store the values you need into the variables. I would suggest to store them in arrays and not variables so you can handle them outside of the foreach loop but that's up to you.
Simple parser for You
$arr1 = explode (",","[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"); // making array with elements like : [0] => "[2018-05-08][1][17]"
$arr2;
$i = 0;
foreach($arr1 as $item){
$temp = explode ("][",$item); // array with elements like [0] => "[2018-05-08", [1] => "1", [2] => "21]"
$arr2[$i]['date'] = substr( $temp[0], 1 ); // deleting first char( '[' )
$arr2[$i]['meal'] = $temp[1];
$arr2[$i]['option'] = substr($temp[2], 0, -1); // deleting last char( ']' )
$i++;
}
you cannot set array to variable .If you want convert string to array, i think my code example may help you:
$a= "[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$b= explode(",",$a );
foreach ($b as $key =>$value) {
$b[$key] = str_replace("[", " ", $b[$key]);
$b[$key] = str_replace("]", " ", $b[$key]);
$b[$key] =explode(" ",trim($b[$key]) );
}
print_r($b);
$results = array_map(
function ($res) {
$res = rtrim($res, ']');
$res = ltrim($res, '[');
return explode('][', $res);
},
explode(',', $yourString)
);
//get variables for first element of array
list($date, $meal, $option) = $results[0];
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
I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?
Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values
You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.
I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php
You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);
foreach($json->entries[0] AS $key => $name) {
echo $key;
}
$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}
Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC
Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.