How to join array values in PHP - php

I have a PHP array:
array
0 =>
array
'cid' => string '18427' (length=5)
1 =>
array
'cid' => string '17004' (length=5)
2 =>
array
'cid' => string '19331' (length=5)
I want to join the values so I can get a string like this:
18427,17004,19331
I tried the implode PHP function, But I get an error:
A PHP Error was encountered
How can join only the values which are in cid?

You have to map the array values first:
echo join(',', array_map(function($item) {
return $item['cid'];
}, $arr));
Without closures it would look like this:
function get_cid($item)
{
return $item['cid'];
}
echo join(',', array_map('get_cid', $arr));
See also: array_map()

You can loop through each element
$result = '';
foreach($array as $sub_array){
$result .= $sub_array['cid'] . ',';
}
$result = substr($result, -2);

// set a new variable for their the value of cid
$cid = array();
// then loop to call them one by one.
foreach($css as $style){
foreach($style as $row){
array_push($cid,$row);
}
}
// then the new $cid array would contain the values of your cid array
$cid = array('1','2','3');
note:then you can now implode or watever you want to get the data set you want..

Related

How to match string to an Array to get the value?

I have an array with corresponding value.
Array
(
[0] => BBsma=200
[1] => SMAperiod=300
[2] => SMA1=400
[3] => SMA2=500
[4] => EMAperiod=300
[5] => EMA1=24
[6] => EMA2=8
)
Now I want to match a certain string like for example BBsma that should return 200. Any help?
Got the array using these codes.
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
array_shift($rows);
INDICATORS.txt content
BBperiod=100
BBsma=200
SMAperiod=300
SMA1=400
SMA2=500
EMAperiod=300
EMA1=24
EMA2=8
After you explode your text to the lines use this code:
for($i=0;$i<sizeof($rows);$i++)
{
$temp=explode("=",$rows[$i]);
if(sizeof($temp)==2)
{
$arr[$temp[0]]=$temp[1];
}
}
You will have named array in $arr
if you want to cast second part to int, you just change 6-line to this:
$arr[$temp[0]]=intval($temp[1]);
You could iterate over every line of your array and find the value with a regular match.
Code:
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
/*
$rows = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
*/
foreach ($rows as $k=>$v) {
if (preg_match("/(BBsma|SMAperiod|EMAperiod)=([0-9]+)/", $v, $matches)) {
echo "found value " . $matches[2] . " for entry " . $matches[1] . " in line " . $k . PHP_EOL;
}
}
Output:
found value 200 for entry BBsma in line 0
found value 300 for entry SMAperiod in line 1
found value 300 for entry EMAperiod in line 4
You can explode by new line as PHP_EOL like this
$col = "BBsma";
$val = "";
foreach(explode(PHP_EOL,$str) as $row){
$cols = explode("=",$row);
if(trim($cols[0]) == $col){
$val = $cols[1];
break;
}
}
echo "Value $col is : $val";
Live Demo
If your going to use the array a few times, it may be easier to read the file into an associative array in the first place...
$rows = [];
$file = "INDICATORS.txt";
$data = file($file, FILE_IGNORE_NEW_LINES);
foreach ( $data as $item ) {
$row = explode("=", $item);
$rows [$row[0]] = $row[1];
}
echo "EMA1 =".$rows['EMA1'];
This doesn't do the array_shift() but not sure why it's used, but easy to add back in.
This outputs...
EMA1 =24
I think that using array filter answers your question the best. It returns an array of strings with status code 200. If you wanted to have better control later on and sort / search through codes. I would recommend using array_walk to create some sort of multi dimensional array. Either solution will work.
<?php
$arr = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
$filtered = array_filter($arr,"filter");
function filter($element) {
return strpos($element,"=200");
}
var_dump($filtered); // Returns array with all matching =200 codes: BBSMA=200
Output:
array (size=1)
0 => string 'BBsma=200' (length=9)
Should you want to do more I would recommend doing something like this:
///////// WALK The array for better control / manipulation
$walked = [];
array_walk($arr, function($item, $key) use (&$walked) {
list($key,$value) = explode("=", $item);
$walked[$key] = $value;
});
var_dump($walked);
This is going to give you an array with the parameter as the key and status code as it's value. I originally posted array_map but quickly realized array walk was a cleaner solution.
array (size=7)
'BBsma' => string '200' (length=3)
'SMAperiod' => string '300' (length=3)
'SMA1' => string '400' (length=3)
'SMA2' => string '500' (length=3)
'EMAperiod' => string '300' (length=3)
'EMA1' => string '24' (length=2)
'EMA2' => string '8' (length=1)
Working with the array becomes a lot easier this way:
echo $walked['BBsma']; // 200
$anything = array("BBsma"=>"200", "SMAperiod"=>"300", "SMA1"=>"400");
echo "the value is " . $anything['BBsma'];
This will return 200

imploding an array to echo a string

I'm trying to print the values from an array as a string. I got this code from the PHP documents, but I'm getting a string conversion error. The values are numbers and I can see them
$viz_array_qry = "SELECT (`column_name`) FROM table_name WHERE option_name='$option_name'";
$result = mysql_query($viz_array_qry);
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
$viz_array = implode (',',$result_array);
}
print_r($viz_array);
//echo $viz_array; <!-- no result-->
If I var_dump the $result_array I get the list of the values below. But I just want to display them as
0,0,57,39,40
I cant work out why the implode it not working?
array (size=5)
0 =>
array (size=1)
'column_name' => string '0' (length=1)
1 =>
array (size=1)
'column_name' => string '0' (length=1)
2 =>
array (size=1)
'column_name' => string '57' (length=2)
3 =>
array (size=1)
'column_name' => string '39' (length=2)
4 =>
array (size=1)
'column_name' => string '40' (length=2)
You should only store value of column_name ($row['column_name']) instead of $row (which is an array) and move implode outside of loop
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row['column_name'];
}
echo implode(',', $result_array);
Implode after the While loop:
$viz_array_qry = "SELECT (`column_name`) FROM table_name WHERE option_name='$option_name'";
$result = mysql_query($viz_array_qry);
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
$viz_array = implode (',',$result_array);
print_r($viz_array);
Even if you do not want to change the existing code and store the data in the array as you are doing you can use array_map() to get the result as you want as below
$arr = array(0=>array('column_name'=>'0'),1=>array('column_name'=>'0'),
3=>array('column_name'=>'57'),4=>array('column_name'=>'39'));
function get_col($col) {
return $col["column_name"];
}
$values = implode(array_map("get_col", $arr), ',');
echo $values ;

How to save json_decoded values (only) as one string into a $var

Im receiving the following variable sent as a json array from javascript: $_REQUEST['fb_friend_uid']
I then decode the array and then do a var_dump
$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);
var_dump($result);
The var_dump shows me the following
array (size=360)
0 =>
array (size=1)
'id' => string '263901486' (length=9)
1 =>
array (size=1)
'id' => string '502533736' (length=9)
2 =>
array (size=1)
'id' => string '506526230' (length=9)
3 =>
array (size=1)
'id' => string '507245473' (length=9)
etc..
How would I go about saving all values from 'id' into one new $var_string ? - formatted like: "263901486, 502533736, 506526230"
Objective is to use the string in an sql query like so:
SELECT * FROM vote WHERE
vote_fb_uid IN ($var_string)
Try this :
$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);
$res_array = array();
foreach($result as $val){
$res_array[] = $val['id'];
}
$res_string = implode(",",$res_array);
If you want all the items to be combined to one long string you can try imploding the array
http://php.net/manual/en/function.implode.php
$varString = implode(',', $_REQUEST['fb_friend_uid'])
I don't really know PHP, but looking at the docs, you should be able to write something along the lines of:
$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);
$res_array = array_map(function ($val) { return $val['id']; });
$res_string = join(",", $res_array);
(Adapted from Prasanth Bendra's answer.)
Try this
$string = json_encode($ar);
$result = json_decode($string, true);
$res_array = array();
foreach($result as $val){
$res_array[] = $val['id'];
}
$res_string = "'".implode("','", $res_array)."'";
$qry = "SELECT * FROM vote WHERE vote_fb_uid IN ($res_string)";

Comma separated list from array [duplicate]

This question already has answers here:
Create a comma-separated string from a single column of an array of objects
(15 answers)
Closed 7 months ago.
I am wondering how to:
Make comma-separated list
Strip last comma from list
Here's an array example:
Array
(
[name] => Array
(
[0] => Some message to display1
)
[test] => Array
(
[0] => Some message to display2
)
[kudos] => Array
(
[0] => Some message to display3
)
)
I want to display it like this:
Comma-List: Some message to display1, Some message to display2, Some message to display3
Loop through the arrays and implode() after you've got each array.
$bigArray = array();
foreach($firstArray as $secondArray){
if(is_array($secondArray)){
$bigArray = array_merge($bigArray, $secondArray);
}
}
$commaList = implode(",", $bigArray);
so, revising my answer to actually address your question, you could do it with nested foreach loops like this:
<?php
$a1 = array(
'name' => array( 0 => 'Some message to display1'),
'test' => array( 0 => 'Some message to display2'),
'kudos' => array( 0 => 'Some message to display3'),
);
$final = "";
foreach($a1 as $innerarray){
foreach($innerarray as $message){
$final .= $message.", ";
}
}
echo substr($final,0,-2);
?>
You can use implode to join values and array_map to extract them:
// this should be your array
$youArray = array();
// return first elements
$values = array_map(function($item) { return $item[0]; }, $youArray);
// echo joined values
echo implode(',', $values);
$array = array("some text","other text");
$impl = implode(",", $array);
echo $impl;
implode works on 1D arrays, but you have a 2D array, this will take a bit more work.
You can use array_map to flatten the array
$flatArray = array_map(function($a){
// I implode here just in case the arrays
// have more than one element, if it's just one
// you can return '$a[0];' instead
return implode(',', $a);
}, $array);
echo implode(',', $flatArray);
This works for your array and should work for arrays that are n levels deep:
$array = array(
'name' => array('Some message to display1'),
'test' => array('Some message to display2'),
'kudos' => array('Some message to display3')
);
$mystr = multi_join($array);
while (substr($mystr, -1) == ',') {
$mystr = substr($mystr, 0, -1);
}
echo $mystr;
function multi_join($value) {
$string = '';
if (is_array($value)) {
foreach ($value as $el) {
$string.= multi_join($el);
}
} else {
$string.= $value.',';
}
return $string;
}
Simplest for your specific sample data would be to access the 0 column of data and implode that. (Demo)
echo implode(', ', array_column($array, 0));
Here are a couple of additional techniques to add to this heap...
Reindex the first level because the splat operator doesn't like associative keys, then merge the unpacked subarrays, and implode.
Use array_reduce() to iterate the first level and extract the first element from each subarray, delimiting as desired without the use of implode().
Codes: (Demo)
$array = [
'name' => ['Some message to display1'],
'test' => ['Some message to display2'],
'kudos' => ['Some message to display3']
];
echo implode(', ', array_merge(...array_values($array)));
echo "\n---\n";
echo array_reduce($array, function($carry, $item) {return $carry .= ($carry ? ', ' : '') . $item[0]; }, '');
Output:
Some message to display1, Some message to display2, Some message to display3
---
Some message to display1, Some message to display2, Some message to display3
The first technique will accommodate multiple elements in the subarrays, the second will not acknowledge more than one "message" per subarray.

php-get data from form through get method

test.php?t=xxx,y=sss
This is how the user inputs data to my script.
How can I get this data as an array inside test.php, and remove the commas?
$temp = explode(',', $_GET['t']);
$t = $temp[0];
$y = substr($temp[1],2);
will get you what you want from the url you gave, however #Tudor Constantin has the best solution.
Edit
This will loop through all however many fields you have. They will finish up in $result in the correct order.
$temp = explode(',', $_GET['t']);
foreach($temp as $var){
if(strpos($var, '=')){
$exp = explode('=', $var);
$result[] = $exp[1];
} else $result[] = $var;
}
then var_dump $result gives this result
array
0 => string 'xxx' (length=3)
1 => string 'sss' (length=3)
2 => string 'ttt' (length=3)
3 => string 'uuu' (length=3)
Edit 2
Or you could try this:-
Say URL is "test.php?t=xxx,y=sss,z=ttt,a=uuu"
$temp = explode(',', $_GET['t']);
$key = array_keys($_GET);
$temp = array_reverse($temp);
$result[$key[0]] = array_pop($temp);
array_reverse($temp);
foreach($temp as $var){
$exp = explode('=', $var);
$result[$exp[0]] = $exp[1];
}
Then var_dump($result); will give you:-
array
't' => string 'xxx' (length=3)
'a' => string 'uuu' (length=3)
'z' => string 'ttt' (length=3)
'y' => string 'sss' (length=3)
By accessing $_GET['t'], you will get the value 'xxx,y=sss' - I think you have to change the URL to something like
test.php?t=xxx&y=sss
So you will be able to access $_GET['t'] and get the value 'xxx' and $_GET['y'] having value 'sss'
You could also send all the parameter values to one variable, separated by '|' for example - then split by that char:
URL would be test.php?array=xxx|sss|ddd|rrr and in test.php you will do:
$arr = explode('|', $_GET['array']);
This way in the $arr variable you will have an array of the values sent (no matter how many are there)

Categories