Count number of elements in array - php

I have this in my DB: 3,14,12,13
Called $user['buddylist']
And this is my code, but the output is 1 instead of 4, What's wrong?
$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );
$nr = count($following);
The output of $foll is "3","14","12","13", :/

Because foll is a string when you do this:
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
You are creating an array with one element when you do this:
$following = array($foll );
If you want to count, you need to count the array before you turn it into a string:
$prefix = '"';
$tag = explode( ',', $user['buddylist'] );
$nr = count($tag);
$foll = $prefix . implode( '",' . $prefix, $tag ) . '",';
$following = array($foll );
I would probably code it like this:
class Buddies {
private $buddies;
public function __construct($buddy_list_string) {
$this->buddies = explode( ',', $buddy_list_string);
}
public function count() {
return count($this->buddies);
}
public function __toString() {
return '"' . implode('","', $this->buddies) . '"';
}
public function toArray() {
return $this->buddies;
}
}
$buddies = new Buddies($user['buddylist']);
echo $buddies->count(); //4
echo $buddies; //"3","14","12","13"
foreach($buddies->toArray() as $buddy) {
//do stuff
}

Related

Proper way to pass an array

This one is boggling me, because I think the code is right but something just isn't clicking, this is a code I picked up from Yanick Rochon and it works when the array is hard coded (in the commented out area) but when I push together the array from all of the pa_mymelp terms it doesn't behave as expected, it uses the entire line as an item vs multiple items per line, and does not create children either, wonder why.. thank you!:
<?php
$thearray = array();
$terms = get_terms("pa_mymelp");
foreach ( $terms as $term ) {
$categories = $term->name;
array_push($thearray, $categories);
}
$categoryLines = $thearray;
/*$categoryLines = array(
"Dodge>2002>Ram 3500>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler",
"Dodge>2001>Ram 2500>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler"
);*/
function buildCategoryTree($categoryLines, $separator) {
$catTree = array();
foreach ($categoryLines as $catLine) {
$path = explode($separator, $catLine);
$node = & $catTree;
foreach ($path as $cat) {
$cat = trim($cat);
if (!isset($node[$cat])) {
$node[$cat] = array();
}
$node = & $node[$cat];
}
}
return $catTree;
}
function displayCategoryTree($categoryTree, $indent = '') {
foreach ($categoryTree as $node => $children) {
echo $indent . $node . "\n";
displayCategoryTree($children, $indent . '|- ');
}
}
$categoryTree = buildCategoryTree($categoryLines, '>');
function displayHtmlCategoryTree($categoryTree, $id = null, $pathSeparator = '>', $parents = '') {
if (empty($categoryTree)) return '';
$str = '<ul' . (!empty($id) ? ' id="'.$id.'"' : '') . '>';
foreach ($categoryTree as $node => $children) {
$currentPath = $parents . (empty($parents) ? '' : $pathSeparator) . $node;
$str .= '<li title="' . $currentPath . '">' . $node .
displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath) .
'</li>';
}
$str .= '</ul>';
return $str;
}
echo displayHtmlCategoryTree($categoryTree, "test", '>');
?>

how to separate data with Quotations marks in php

I have a variable
<?php
$srch_key = 'asdfggfdsa' ;
?>
Now I want to make a separation with comma after 5 letters. For this I have done this code.
<?php
function ref_format($str, $step, $reverse = false) {
if ($reverse)
return strrev(chunk_split(strrev($str), $step, ','));
return chunk_split($str, $step, ',');
}
$passport = ref_format("$srch_key", 5);
echo $passport_key = substr($passport, 0, -1);
?>
The Output seems like this
asdfg,gfdsa
But I want to make the output like this
'asdfg','gfdsa'
How can I make this.
$srch_key = 'asdfggfdsa' ;
$arr = str_split($srch_key, "5");
$res = "'" . implode ( "', '", $arr ) . "'";
echo $res;
You could do this using implode() and str_split():
function ref_format($str, $step, $reverse = false)
{
if ($reverse)
return strrev("'" . implode("','", str_split($str, $step)) . "'");
return "'" . implode("','", str_split($str, $step)) . "'";
}

Update data dynamically

public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
}
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
Got error
Fatal error: [] operator not supported for strings
Tweaked code from add function which worked. Wanted to have fields and values updated dynamically without using variables, i.e. $_POST['address'].
$query .= $fields . "=" . $values . ", ";
seem not to be working. Not sure what cause the error: Fatal error: [] operator not supported for strings. How to insert field = value in sql query?
Use like this
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$query .= $key . "='" . $data[$key] . "' ,";
}
}
$query = substr($query,0,strlen($query)-1);
$query = $query . " WHERE id = '".$id."' ";
Look at the foreach loop!!!
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields); // Mistake done here
$values = implode(" ", $values); // Mistake done here
$query .= $fields . "=" . $values . ",";
}
Change your those two line and the next line outside the loop. May be this solve your problem.
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
Follow my code. Where no need implementation implode() function. I have changed your function code. try it.
public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$queryArr[] = $key . "='" . $this->db->real_escape_string($data[$key]);
}
}
$query = implode(" ,", $queryArr);
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}

Insert data on mysql using mysqli function

how i can make a insert using this fuctions
I m learning php, as using this functions (mysqli abstract) but after update wont work any more.
/** insert data array */
public function insert(array $arr)
{
if ($arr)
{
$q = $this->make_insert_query($arr);
$return = $this->modifying_query($q);
$this->autoreset();
return $return;
}
else
{
$this->autoreset();
return false;
}
}
complement
/** insert query constructor */
protected function make_insert_query($data)
{
$this->get_table_info();
$this->set_field_types();
if (!is_array(reset($data)))
{
$data = array($data);
}
$keys = array();
$values = array();
$keys_set = false;
foreach ($data as $data_key => $data_item)
{
$values[$data_key] = array();
$fdata = $this->parse_field_names($data);
foreach ($fdata as $key => $val)
{
if (!$keys_set)
{
if (isset($this->field_type[$key]))
{
$keys[] = '`' . $val['table'] . '`.`' . $val['field'] . '`';
}
else
{
$keys[] = '`' . $val['field'] . '`';
}
}
$values[$data_key][] = $this->escape($val['value'], $this->is_noquotes($key), $this->field_type($key), $this->is_null($key),
$this->is_bit($key));
}
$keys_set = true;
$values[$data_key] = '(' . implode(',', $values[$data_key]) . ')';
}
$ignore = $this->ignore ? ' IGNORE' : '';
$delayed = $this->delayed ? ' DELAYED' : '';
$query = 'INSERT' . $ignore . $delayed . ' INTO `' . $this->table . '` (' . implode(',', $keys) . ') VALUES ' . implode(',',
$values);
return $query;
}
before update this class i used to insert data like this
$db = Sdba::table('users');
$data = array('name'=>'adam');
$db->insert($data);
this method of insert dont works on new class.
if i try like this i got empty columns and empty values.
thanks for any help
complete class download http://goo.gl/GK3s4E
Try using set instead of insert:
$users = Sdba::table('users');
$user['name'] = 'Alvaro';
$users->set($user);

var_export prettifier / visualizer

I'm using var_export to dump output to logs when errors occur. However since the result is in pure text, I don't get a chance to push it through some sort of library like krumo so I can interactively explores the output.
What methods do people have to deal with making var_export text more readable?
Here is my function, it works well for multidimensional arrays:
function VE($varname, $varval, $short_syntax=true, $tag = ' ', $comma='', $end_line="\r\n") {
$res = '';
if($short_syntax){
$begin_array = '[';
$end_array = ']';
} else {
$begin_array = 'array(';
$end_array = ')';
}
$arr = explode('/',$varname);
$dim =count($arr)-1;
$lastKey = end($arr);
if (! is_array($varval)){
if( is_string($varval)) $varval = "'$varval'";
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $varval . $comma . $end_line;
}else{
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $begin_array . $end_line;
$count_varval = 0;
$dim_varval = count($varval);
foreach ($varval as $key => $val){
$count_varval++;
if($count_varval<$dim_varval) $commma=','; else $commma='';
if( is_string($key)) $key = "'$key'";
$res .= VE ($varname . "/" . $key , $val, $short_syntax, $tag, $commma);
}
$res .= str_repeat($tag,$dim) . $end_array . $comma . $end_line;
}
return $res;
}
$bigarray = array(); // your array
$bb = VE ('$bigarray', $bigarray);
echo "<pre>$bb</pre>";
I hope it helps ;)

Categories