Express function as a variable - php

I dont know exactly how to put this. I have this function:
protected function _do_thumb($temaid)
{
$firstPost = $this->registry->topics->getPostById( $temaid );
preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $firstPost['post'], $match);
return $match[1];
}
[...]
while ( $i = $this->DB->fetch() )
{
$forum = $this->registry->class_forums->forum_by_id[ $i['forum_id'] ];
if ( $this->registry->permissions->check( 'read', $forum ) != TRUE )
{
continue;
}
if ( $forum['password'] != "" )
{
continue;
}
$to_echo .= $this->_parseTemplate( $row, array (
'topic_title' => str_replace( '&#', '&#', $i['title'] ),
'topic_id' => $i['tid'],
'topic_link' => "showtopic=".$i['tid'],
'forum_title' => htmlspecialchars($forum['name']),
'forum_id' => $i['forum_id'],
'last_poster_id' => $i['last_poster_id'],
'last_post_name' => $i['last_poster_name'],
'last_post_time' => $this->registry->getClass('class_localization')->getDate( $i['last_post'] , 'LONG', 1 ),
'timestamp' => $i['start_date'],
'starter_id' => $i['starter_id'],
'starter_name' => $i['starter_name'],
'board_url' => $this->settings['board_url'],
'board_name' => $this->settings['board_name'],
'rfc_date' => date( 'j\-M\-Y', $i['start_date']),
'thumb' => $this->_do_thumb($i['topic_firstpost'])
) ) . "\r\n";
}
$firstPost is supposed to produce a value result of another function. The problem here is that that function seems to stop halfway the whole loop so it returns an incomplete result, only the first element of a list. $forum however works fine because it is expressed as a variable so I believe the solution might be to express $topic in the same way. Something like this:
$this->registry->topics->getPostById[ $temaid ];
However, I dont know how I ought do it. Is it even possible?
Thank you.

getBostById() and $i = $this->DB->fetch() in while loop where you call getPostById(), they both use $this->DB to store information from Database.
And when called getPostById(), it overrides information inside of $this->DB and moves hidden pointer to the end. This function returns POST data from database, and also uses something like $i = $this->DB->fetch() for this. Therefore pointer to data moves to the end.
Next, time when $i = $this->DB->fetch() called, it sees pointer at the end, and stop looping.
Solution is, when fetching result from database, don't override it. There for cache them before calling getPostById:
//while ( $i = $this->DB->fetch() )
$items = array();
$counter = 0 ;
while ($i = $this->DB->fetch()) {
$items[$counter++] = $i;
}
foreach ( $items as $i ){
$forum = $this->registry->class_forums->forum_by_id[ $i['forum_id'] ];
if ( $this->registry->permissions->check( 'read', $forum ) != TRUE )
{
continue;
}
if ( $forum['password'] != "" )
{
continue;
}
$to_echo .= $this->_parseTemplate( $row, array (
'topic_title' => str_replace( '&#', '&#', $i['title'] ),
'topic_id' => $i['tid'],
'topic_link' => "showtopic=".$i['tid'],
'forum_title' => htmlspecialchars($forum['name']),
'forum_id' => $i['forum_id'],
'last_poster_id' => $i['last_poster_id'],
'last_post_name' => $i['last_poster_name'],
'last_post_time' => $this->registry->getClass('class_localization')->getDate( $i['last_post'] , 'LONG', 1 ),
'timestamp' => $i['start_date'],
'starter_id' => $i['starter_id'],
'starter_name' => $i['starter_name'],
'board_url' => $this->settings['board_url'],
'board_name' => $this->settings['board_name'],
'rfc_date' => date( 'j\-M\-Y', $i['start_date']),
'thumb' => $this->_do_thumb($i['topic_firstpost'])
) ) . "\r\n";
}

Related

How do I convert a string of an array to an array in PHP?

This seems like a simple task, but I haven't been able to find a way to do this. I have an output of data stored as a string like this:
$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";
What I simply need to do is convert it to this array:
$arrData = array('first' => "$first", 'middle' => "$middle", 'last' => "$last");
The closest I have been able to get is this shown below with print_r results:
$Data = explode(',', $rawData);
Array
(
[0] => 'first' => '$first'
[1] => 'middle' => '$middle'
[2] => 'last' => '$last'
)
What I need is this:
Array
(
[first] => $first
[middle] => $middle
[last] => $last
)
Must be something very easy I have overlooked. Please help.
Depending on where you get the string from, you may use eval. It's highly recommended to not use this function, whenever the contents of that string may be influenced directly or indirectly by a user, see hint at http://php.net/manual/en/function.eval.php. And it must contain valid PHP syntax, thus putting it into a try/catch block is necessary:
$evalArray = false;
$first = 'a';
$middle = 'b';
$last = 'c';
$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";
try {
$evalArray = eval($rawData);
} catch ( $e )
{
echo "parsing failed " . $e
}
print_r($evalArray );
This does what you want ( i think ), even if its not pretty
<?php
$arr = array();
$first = 'one';
$middle = 'two';
$last = 'three';
$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";
$arrData = explode( ',', ( str_replace( array( 'array(\'', '=>', '\')', '\'' ), array( '', '%##%', '', '' ), $rawData ) ) );
foreach( $arrData as $val ) {
$v = explode( '%##%', $val );
$arr[trim($v[0])] = trim($v[1]);
}
echo '<pre>' . print_r( $arr, true ) . '</pre>';
?>

Dynamic variables in looper

This is my simple looper code
foreach( $cloud as $item ) {
if ($item['tagname'] == 'nicetag') {
echo $item['tagname'];
foreach( $cloud as $item ) {
echo $item['desc'].'-'.$item['date'];
}
} else
//...
}
I need to use if method in this looper to get tags with same names but diferent descriptions and dates. The problem is that I dont know every tag name becouse any user is allowed to create this tags.
Im not really php developer so I'm sory if it's to dummies question and thanks for any answers!
One possible solution is to declare a temporary variable that will hold tagname that is currently looped through:
$currentTagName = '';
foreach( $cloud as $item ) {
if ($item['tagname'] != $currentTagName) {
echo $item['tagname'];
$currentTagName = $item['tagname'];
}
echo $item['desc'] . '-' . $item['date'];
}
I presume that your array structure is as follows:
$cloud array(
array('tagname' => 'tag', 'desc' => 'the_desc', 'date' => 'the_date'),
array('tagname' => 'tag', 'desc' => 'the_desc_2', 'date' => 'the_date_2'),
...
);
BUT
This solution raises a problem - if your array is not sorted by a tagname, you might get duplicate tagnames.
So the better solution would be to redefine your array structure like this:
$cloud array(
'tagname' => array (
array('desc' => 'the_desc', 'date' => 'the_date'),
array('desc' => 'the_desc_2', 'date' => 'the_date_2')
),
'another_tagname' => array (
array('desc' => 'the_desc_3', 'date' => 'the_date_3'),
...
)
);
and then you can get the data like this:
foreach ($cloud as $tagname => $items) {
echo $tagname;
foreach($items as $item) {
echo $item['desc'] . '-' . $item['date'];
}
}

PHP - Create Hierarchal Array

I'm not even sure how to begin wording this question, but basically, I have an array, that looks like this:
Array
(
[0] => /
[1] => /404/
[2] => /abstracts/
[3] => /abstracts/edit/
[4] => /abstracts/review/
[5] => /abstracts/view/
[6] => /admin/
[7] => /admin/ads/
[8] => /admin/ads/clickcounter/
[9] => /admin/ads/delete/
[10] => /admin/ads/edit/
[11] => /admin/ads/list/
[12] => /admin/ads/new/
[13] => /admin/ads/sponsordelete/
[14] => /admin/ads/sponsoredit/
[15] => /admin/ads/sponsornew/
[16] => /admin/ads/stats/
[17] => /admin/boilerplates/
[18] => /admin/boilerplates/deleteboiler/
[19] => /admin/boilerplates/editboiler/
[20] => /admin/boilerplates/newboilerplate/
[21] => /admin/calendar/event/add/
[22] => /admin/calendar/event/copy/
)
And I need to 'reduce' / 'process' it into an array that looks like this:
Array
(
[''] => Array()
['404'] => Array()
['abstracts'] => Array
(
[''] => Array()
['edit'] => Array()
['review'] => Array()
['view'] => Array()
)
['admin'] => Array
(
['ads'] => Array
(
[''] => Array()
['clickcounter'] => Array()
['delete'] =>Array()
['edit'] => Array()
)
)
.....
.....
)
That, if manually initialized would look something like this:
$urlTree = array( '' => array(),
'404' => array(),
'abstracts'=> array( '' => array(),
'edit' => array(),
'review'=> array(),
'view' => array() ),
'admin' => array( 'ads'=> array( '' => array(),
'clickcounter'=> array(),
'delete' => array(),
'edit' => array() ) )
);
I usually stray away from asking straight up for a chunk of code on SO, but does anyone perhaps have any advice / code that can traverse my array and convert it to a hierarchy?
EDIT: Here is the bit I have right now, which, I know is pitifully small, I'm just blanking out today it seems.
function loadUrlData()
{
// hold the raw data, /blah/blah/
$urlData = array();
$res = sql::query( "SELECT DISTINCT(`url`) FROM `pages` ORDER BY `url` ASC" );
while( $row = sql::getarray( $res ) )
{
$urlData[] = explode( '/', substr( $row['url'], 1, -1 ) );
}
// populated, eventually, with the parent > child data
$treeData = array();
// a url
foreach( $urlData as $k=> $v )
{
// the url pieces
foreach( $v as $k2=> $v2 )
{
}
}
// $treeData eventually
return $urlData;
}
Looks rather easy. You want to loop through all lines (foreach), split them into parts (explode), loop through them (foreach) and categorize them.
Since you don't like asking for a chunk of code, I won't provide any.
Update
A very nice way to solve this is to reference the $urlTree (use &), loop through every part of the URL and keep updating a variable like $currentPosition to the current part in the URL tree. Because you use &, you can simply edit the array directly while still using a simple variable.
Update 2
This might work:
// a url
foreach( $urlData as $k=> $v )
{
$currentSection = &$treeData;
// the url pieces
foreach( $v as $k2=> $v2 )
{
if (!isset($currentSection[$v2])) {
$currentSection[$v2] = array();
}
$currentSection = &$currentSection[$v2];
}
}
I know you didn't ask for a chunk of code, but I'd just call this a petit serving:
$map = array();
foreach($urls as $url) {
$folders = explode('/', trim($url, '/'));
applyChain($map, $folders, array());
}
function applyChain(&$arr, $indexes, $value) { //Here's your recursion
if(!is_array($indexes)) {
return;
}
if(count($indexes) == 0) {
$arr = $value;
} else {
applyChain($arr[array_shift($indexes)], $indexes, $value);
}
}
It's fairly simple. We separate each url into its folders (removing trailing and leading slashes) and then work our way down the array chain until we reach the folder mentioned in the URL. Then we place a new empty array there and continue to the next URL.
My version:
$paths = array(
0 => '/',
1 => '/404/',
2 => '/abstracts/',
3 => '/abstracts/edit/',
4 => '/abstracts/review/',
5 => '/abstracts/view/',
6 => '/admin/',
7 => '/admin/ads/',
// ....
);
$tree = array();
foreach($paths as $path){
$tmp = &$tree;
$pathParts = explode('/', rtrim($path, '/'));
foreach($pathParts as $pathPart){
if(!array_key_exists($pathPart, $tmp)){
$tmp[$pathPart] = array();
}
$tmp = &$tmp[$pathPart];
}
}
echo json_encode($tree, JSON_PRETTY_PRINT);
https://ideone.com/So1HLm
http://ideone.com/S9pWw
$arr = array(
'/',
'/404/',
'/abstracts/',
'/abstracts/edit/',
'/abstracts/review/',
'/abstracts/view/',
'/admin/',
'/admin/ads/',
'/admin/ads/clickcounter/',
'/admin/ads/delete/',
'/admin/ads/edit/',
'/admin/ads/list/',
'/admin/ads/new/',
'/admin/ads/sponsordelete/',
'/admin/ads/sponsoredit/',
'/admin/ads/sponsornew/',
'/admin/ads/stats/',
'/admin/boilerplates/',
'/admin/boilerplates/deleteboiler/',
'/admin/boilerplates/editboiler/',
'/admin/boilerplates/newboilerplate/',
'/admin/calendar/event/add/',
'/admin/calendar/event/copy/');
$result = array();
foreach ($arr as $node) {
$result = magic($node, $result);
}
var_dump($result);
function magic($node, $tree)
{
$path = explode('/', rtrim($node, '/'));
$original =& $tree;
foreach ($path as $node) {
if (!array_key_exists($node, $tree)) {
$tree[$node] = array();
}
if ($node) {
$tree =& $tree[$node];
}
}
return $original;
}
<?php
$old_array = array("/", "/404/", "/abstracts/", "/abstracts/edit/", "/abstracts/review/", "/rrl/");
$new_array = array();
foreach($old_array as $woot) {
$segments = explode('/', $woot);
$current = &$new_array;
for($i=1; $i<sizeof($segments); $i++) {
if(!isset($current[$segments[$i]])){
$current[$segments[$i]] = array();
}
$current = &$current[$segments[$i]];
}
}
print_r($new_array);
?>
You might consider converting your text to a JSON string, then using json_decode() to generate the structure.

Most efficient way to replace empty values in an array

Is there a better way of doing this PHP code? What I'm doing is looping through the array and replacing the "title" field if it's blank.
if($result)
{
$count = 0;
foreach($result as $result_row)
{
if( !$result_row["title"] )
{
$result[$count]["title"] = "untitled";
}
$count++;
}
}
Where $result is an array with data like this:
Array
(
[0] => Array
(
[title] => sdsdsdsd
[body] => ssdsd
)
[1] => Array
(
[title] => sdssdsfds
[body] => sdsdsd
)
)
I'm not an experienced PHP developer, but I guess that the way I've proposed above isn't the most efficient?
Thanks
if($result) {
foreach($result as $index=>$result_row) {
if( !$result_row["title"] ) {
$result[$index]["title"] = "untitled";
}
}
}
You don't need to count it. It's efficient.
if ($result)
{
foreach($result as &$result_row)
{
if(!$result_row['title'])
{
$result_row['title'] = 'untitled';
}
}
}
Also, you may want to use something other than a boolean cast to check the existence of a title in case some young punk director releases a movie called 0.
You could do something like if (trim($result_row['title']) == '')
Mixing in a little more to #Luke's answer...
if($result) {
foreach($result as &$result_row) { // <--- Add & here
if($result_row['title'] == '') {
$result_row['title'] = 'untitled';
}
}
}
The key is the & before $result_row in the foreach statement. This make it a foreach by reference. Without that, the value of $result_row is a copy, not the original. Your loop will finish and do all the processing but it won't be kept.
The only way to get more efficient is to look at where the data comes from. If you're retrieving it from a database, could you potentially save each record with an "untitled" value as the default so you don't need to go back and put in the value later?
Another alternative could be json_encode + str_replace() and then json_decode():
$data = array
(
0 => array
(
'title' => '',
'body' => 'empty',
),
1 => array
(
'title' => 'set',
'body' => 'not-empty',
),
);
$data = json_encode($data); // [{"title":"","body":"empty"},{"title":"set","body":"not-empty"}]
$data = json_decode(str_replace('"title":""', '"title":"untitled"', $data), true);
As a one-liner:
$data = json_decode(str_replace('"title":""', '"title":"untitled"', json_encode($data)), true);
Output:
Array
(
[0] => Array
(
[title] => untitled
[body] => empty
)
[1] => Array
(
[title] => set
[body] => not-empty
)
)
I'm not sure if this is more efficient (I doubt it, but you can benchmark it), but at least it's a different way of doing the same and should work fine - you have to care about multi-dimensional arrays if you use the title index elsewhere thought.
Perhaps array_walk_recursive:
<?php
$myArr = array (array("title" => "sdsdsdsd", "body" => "ssdsd"),
array("title" => "", "body" => "sdsdsd") );
array_walk_recursive($myArr, "convertTitle");
var_dump($myArr);
function convertTitle(&$item, $key) {
if ($key=='title' && empty($item)) {$item = "untitled";}
}
?>
If you want sweet and short, try this one
$result = array(
array(
'title' => 'foo',
'body' => 'bar'
),
array(
'body' => 'baz'
),
array(
'body' => 'qux'
),
);
foreach($result as &$entry) if (empty($entry['title'])) {
$entry['title'] = 'no val';
}
var_dump($records);
the empty() will do the job, see the doc http://www.php.net/manual/en/function.empty.php

summarise php array into treeview

Array
(
[00000000017] => Array
(
[00000000018] => Array
(
[00000000035] => I-0SAYHADW4JJA
[00000000038] => I-RF10EHE25KY0
[00000000039] => I-8MG3B1GT406F
)
[00000000019] => I-7GM4G5N3SDJL
)
[00000000025] => Array
(
[00000000011] => I-HT34P06WNMGJ
[00000000029] => I-U5KKT1H8J39W
)
[00000000040] => I-GX43V2WP9KPD
[00000000048] => I-XM526USFJAH9
[00000000052] => I-M414RK3H987U
[00000000055] => I-GABD4G13WHX7
)
I have the above array and i want to create a treeview display..
any recommendation ?
I guess i have to elaborate furthe on my question..
I want to store those array according to the level of array..
Example , I want something look like this :
[level_1]=> 00000000017,00000000025,00000000040, 00000000048, 00000000052
[level_2]=> 00000000018,00000000019, 00000000011, 00000000029
[level_3]=> 00000000035, 00000000038, 00000000039
You want a modified breadth-first search. This has the correct results for your sample structure:
<?php
function BFTraverse(&$tree = NULL, $depth = 0)
{
if (empty($tree))
return FALSE;
$keys = array_keys($tree);
$struct["lvl_$depth"] = $keys;
foreach ($keys as $key)
{
if (is_array($tree[$key]))
{
$struct = array_merge_recursive($struct, BFTraverse($tree[$key], $depth + 1));
}
}
return $struct;
}
$data = array
('00000000017' => array
(
'00000000018' => array
(
'00000000035' => 'I-0SAYHADW4JJA',
'00000000038' => 'I-RF10EHE25KY0',
'00000000039' => 'I-8MG3B1GT406F'
),
'00000000019' => 'I-7GM4G5N3SDJL'
),
'00000000025' => array
(
'00000000011' => 'I-HT34P06WNMGJ',
'00000000029' => 'I-U5KKT1H8J39W'
),
'00000000040' => 'I-GX43V2WP9KPD',
'00000000048' => 'I-XM526USFJAH9',
'00000000052' => 'I-M414RK3H987U',
'00000000055' => 'I-GABD4G13WHX7'
);
$var = BFTraverse($data);
$i = 0;
foreach ($var as $level)
echo "Level " . ++$i . ': ' . implode(', ', $level) . "\n";
?>
The output is:
Level 1: 00000000017, 00000000025, 00000000040, 00000000048, 00000000052, 00000000055
Level 2: 00000000018, 00000000019, 00000000011, 00000000029
Level 3: 00000000035, 00000000038, 00000000039
edit: Modified in the sense that you want the keys and not the node values.
I ran into the same problem recently and this article by Kevin van Zonneveld helped me out.
Basically you have to use a recursive function. Check out the article, it's what you need!

Categories