imploding an array to echo a string - php

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 ;

Related

extract only duplicate value from multidimensional array in php

I have array like this
$non_unique_zip
[0]->[0]91390
[1]ca
[2]1
[1]->[0]91391
[1]ca
[2]1
[2]->[0]91392
[1]ca
[2]1
[3]->[0]91390
[1]ca
[2]2
[4]->[0]91394
[1]ca
[2]2
so basically array has elements where arra[n][0] is zipcode and array[n][2] is buyer_id.
now out of this, i just want the zipcodes which have multiple buyers. so the only thing I want to extract is
[0]->[0]91390
[1]ca
since 91390 is the only zipcode which has buyer as 1 and 2.
I tried
$result = array();
$first = $non_unique_zip[0];
for($i=0; $i<count($non_unique_zip); $i++){
$result = array_intersect ($first, $non_unique_zip[$i]);
$first = $result;
}
but it just gives error undefined offset.
Any help will be appreciated.
If you call $records your starting array, here is a way to get the zips with 3 lines of code:
//array whose keys are zips, and values are # of occurances
$zips = array_count_values(array_column($records,0));
//filter keeps only zips which occur more than once.
$zips = array_filter($zips,function($n){return $n>1;});
//if you only need the zips, you're done! they are the keys
$zips = array_keys($zips);
Live demo
Use an array that keeps track of the zip codes that have already been encountered before. Then when you get a zip that's in that array, you know it's a duplicate.
$zips = array();
$result = array();
foreach ($non_unique_zip as $e) {
$code = $e[0];
if (isset($zips[$code])) { // duplicate, so add to $result
$result[$code] = array($code, $e[1]);
} else {
$zips[$code] = true; // first time, add it to $zips
}
}
Use array_walk like so:
<?php
$non_unique_zip = [
[91390, "ca"],
[91391, "ca"],
[91392, "ca"],
[91390, "ca"],
[91394, "ca"],
];
$unique_zip = [];
$duplicates = [];
array_walk($non_unique_zip, function($data) use(&$unique_zip, &$duplicates){
if(!in_array($data, $unique_zip)){
$unique_zip[] = $data;
}else{
$duplicates[] = $data;
}
});
var_dump( $duplicates );
// PRODUCES::
array (size=1)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
var_dump( $unique_zip );
// PRODUCES::
array (size=4)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
1 =>
array (size=2)
0 => int 91391
1 => string 'ca' (length=2)
2 =>
array (size=2)
0 => int 91392
1 => string 'ca' (length=2)
3 =>
array (size=2)
0 => int 91394
1 => string 'ca' (length=2)

create multi array php with two arrays

I have two arrays same like when var_dump:
$arr1 = array (size=2)
0 => string '10:2'
1 => string '10:1'
$arr2 = array (size=2)
0 => string '[{username:userA,email:userA#gmail.com'
1 => string 'username:userB,email:userB#gmail.com}]'
Now, i want to result same below:
$result = array (size=2)
'10:2' =>
array (size=2)
'username' => string 'userA'
'email' => string 'userA#gmail.com'
'10:1' =>
array (size=2)
'username' => string 'userB'
'email' => string 'userB#gmail.com'
Thanks for help!
I think this should do it:
// Turn string "key1:val1,key2,val2,..." into associative array.
function str_to_assoc($str) {
$str = str_replace(array('[{', '}]'), '', $str); // Remove extranous garbage
$arr = explode(',', $str);
$res = array();
foreach ($arr as $keyvalue) {
list($key, $value) = explode(':', $keyvalue);
$res[$key] = $value;
}
return $res;
$result = array_combine($arr1, array_map('str_to_assoc', $arr2));
It looks like $arr2 came from improperly parsing JSON by hand (maybe using preg_split()?). If you do:
$arr2 = json_decode($json_string);
then you should be able to get your result with just:
$result = array_combine($arr1, $arr2);

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)";

urldecode losses 1 parameter

I'm using urlencode & urldecode to pass variables trough a html-form.
$info = 'tempId='.$rows['tempID'].'&tempType='.$rows['tempType'].'&dbId='.$rows['ID'];
echo '<input type="hidden" name="rank[]" value="'.urlencode($info).'" >';
Here is what is in $rows
array (size=4)
'ID' => string '110' (length=3)
'tempID' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'pageOrder' => string '0' (length=1)
So $info is
tempId=1&tempType=temp_first&dbId=110
But if i then decode it, it losses 1 parameter. How is this possible?
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$tempId = urldecode($param[0]); // template id
$tempType = urldecode($param[1]); // Template type
$dbId = urldecode($param[2]); // database ID
var_dump($param);
}
Output:
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
Sometime there are even things in the array wich should not be in there, for example instead of temp_first it says tempType. Just the variable name.
I hope you guys can help me
There's no need to explode and process the string manually, you can use parse_str():
parse_str(urldecode($list[$i]), $output);
var_dump($output);
Would output:
array
'tempId' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'dbId' => string '110' (length=3)
try this
$result=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$result[$param[0]]=$param[1];
}
var_dump($result);
Could you try this and check the result (I'm groping in the dark though):
//change this <input type="hidden" name="rank[]" value="'.urlencode($info).'" > to
//<input type="hidden" name="urlargs" value="'.urlencode($info).'" >
$values = explode('&',urldecode($_POST['urlargs']));
$arguments = array();
foreach($values as $argument_set){
$data = explode('=',$argument_set);
$arguments[$data[0]] = $data[1];
}
var_dump($arguments);
I believe the problem is in the way you're processing the value
$data=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk); //
$data[$param[0]]=$param[1]
}
Instead of grouping all code together, start by putting it in seperate vars and echo the content for debugging. Because you are saying you loose one variable, but the output you show is just one of the variables. What is the var_dump of the other two?
Because your var_dump($param); would output the part before the '=' and after the '=', so indeed i would expect the output to be something like: So which one of these are you missing?
array (size=2)
0 => string 'tempId' (length=6)
1 => string '1' (length=1)
array (size=2)
0 => string 'tempType' (length=8)
1 => string 'temp_first' (length=10)
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
DEBUG code:
foreach ($list as $row) {
echo 'Full row:: '. $row.'<br>';
//if the data is comming via GET or POST, its already decoded and no need to do it again
$split = explode('&', urldecode($row));
foreach($split as $chunk) {
echo 'Chunk:: '.$chunk.'<br>';
$param = explode('=', $chunk);
echo 'param name:: '.$param[0].'<br>';
echo 'param value:: '.$param[1].'<br>';
}
}

How to join array values in 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..

Categories