Array

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru
Посоветуйте как правильней и лучше оставить. Из двух одинаковых записей какая будет быстрей работать.

PHP:
$temphead = str_replace ('{style_path}', $style_path, $temphead);
$temphead = str_replace ('{style}', $template, $temphead);
$temphead = str_replace ('{page}', $pages, $temphead);
$temphead = str_replace ('{site_url}', $site_url, $temphead);
$temphead = str_replace ('{site_path}', $site_path, $temphead);
$temphead = str_replace ('{title_web}', $title_web, $temphead);
$temphead = str_replace ('{description_web}', $description_web, $temphead);
$temphead = str_replace ('{keyword}', $keyword, $temphead);
$temphead = str_replace ('{language}', $language, $temphead);
$temphead = str_replace ('{loading_start}', $loading_style_start, $temphead);
$temphead = str_replace ('{style_css}', $style_css, $temphead);
$temphead = str_replace ('{date_time}', date($date_format[$date_format_num],time()), $temphead);
 
$templ = str_replace ('{style_path}', $style_path, $templ);
$templ = str_replace ('{style}', $template, $templ);
$templ = str_replace ('{page}', $pages, $templ);
$templ = str_replace ('{site_url}', $site_url, $templ);
$templ = str_replace ('{site_path}', $site_path, $templ);
$templ = str_replace ('{loading_img}', $loading_img, $templ);
$templ = str_replace ('{date_time}', date($date_format[$date_format_num],time()), $templ);
$templ = str_replace ('{SizeText}', $textT, $templ);
 
$tempfoot = str_replace ('{page_line}', $page_line, $tempfoot);
$tempfoot = str_replace ('{timegen}', $timegen, $tempfoot);
$tempfoot = str_replace ('{count_total}', $count_total, $tempfoot);
$tempfoot = str_replace ('{users_online}', $users_online, $tempfoot);
$tempfoot = str_replace ('{date_time}', date($date_format[$date_format_num],time()), $tempfoot);
$tempfoot = str_replace ('{loading_end}', $loading_style_end, $tempfoot);

PHP:
$with_temphead = array(
'{style_path}',
'{style}',
'{page}',
'{site_url}',
'{site_path}',
'{title_web}',
'{description_web}',
'{keyword}',
'{language}',
'{loading_start}',
'{style_css}',
'{date_time}');
$on_to_temphead = array(
$style_path,
$template,
$pages,
$site_url,
$site_path,
$title_web,
$description_web,
$keyword,
$language,
$loading_style_start,
$style_css,date($date_format[$date_format_num],time()));
$temphead = str_replace ($with_temphead,$on_to_temphead,$temphead);
 
$with_templ = array(
'{style_path}',
'{style}',
'{page}',
'{site_url}',
'{site_path}',
'{loading_img}',
'{date_time}',
'{SizeText}');
$on_to_templ = array(
$style_path,
$template,
$pages,
$site_url,
$site_path,
$loading_img,date($date_format[$date_format_num],time()),
$textT);
$templ = str_replace ($with_templ,$on_to_templ,$templ);
 
$with_tempfoot = array('
{page_line}',
'{timegen}',
'{count_total}',
'{users_online}',
'{date_time}',
'{loading_end}');
$on_to_tempfoot = array(
$page_line,
$timegen,
$count_total,
$users_online,
date($date_format[$date_format_num],time()),
$loading_style_end);
$tempfoot = str_replace ($with_tempfoot,$on_to_tempfoot,$tempfoot);
 
Последнее редактирование модератором:

wext

Король пиратов
Пользователь
11 Фев 2005
3.774
22
38
34
grand line
madfrager.ru
ясен красен 2 вариант.

Кстати, ты не забываешь про ссылки на память?

Допустим у нас есть статья:
id date title text
id = integer
date = integer (типо в юникс форме)
title = varchar(64)
text = text()

Далее заменять лучше так:
PHP:
$q = mysql_query("SELECT ...");
$page = str_replace(array('%ID%', '%DATE%', '%TITLE%', '%TEXT%'),
                    array($q['id'], date("d-m-Y H:i:s", $q['date']), htmlspecialchars($q['title'], &$q['text']),
                    &$template);
Почему я вставил ID без ссылки на память? Потому что ссылка на память занимает 32 бита и integer тож 32 бита, разницы в занимаемой памяти нет, зато в скорости доступа есть (при ссылке идет двойное обращение к памяти).
Дату мы налету сконвертили в строку. Чем налету лучше чем в переменную до реплейса - экономим память.
Заголовок опять же очищаем налету.
А вот почему мы вставили ссылку на память с текстом - это огромная экономия памяти, т.к. ее объем достаточно большой и по сути иметь ее в 2 копиях просто нелогично. Т.е. у нас текст есть в главной части программы, нафига при больших объемах его копировать еще раз?
То же самое я сделал и с шаблоном - т.к. он достаточно большой по размерам, то я кинул ссылку на него.
 
  • Like
Реакции: FussesDemon

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru
Есть код

PHP:
$bot=array("Googlebot", "Yandex", "Aport", "StackRambler", "Mozilla/4.0", "Slurp", "bot", "ia_archiver");
foreach($bot as $r) if(stristr($_SERVER['HTTP_USER_AGENT'],$r)){$bot=$r;};
if($bot !="") {
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d.m.Y - H:i:s");
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$from=getenv("HTTP_REFERER");
$to=getenv("SCRIPT_NAME"); 
$fh = fopen($botlog, "r");
$fil = fread($fh, filesize($botlog));
fclose($fh);
$con=$date.":::".$bot.":::".$ip.":::".$home.":::".$from.":::".$to."::: \r\n".$fil;
$botfile=fopen($botlog,"w");
fputs($botfile, $con);
fclose($botfile);
}
Работает вроде но при запросе чего либо чего нет в списке array то на выходе получаем слово array. Как сделать так чтобы если нет в списке то даже и не бытаемся дальше не чего записывать.
 

wext

Король пиратов
Пользователь
11 Фев 2005
3.774
22
38
34
grand line
madfrager.ru
Есть такая интересная фанукция как in_array. Посмотри.

Кстати, а нафига ты читаешь файлы вот так вот?:
PHP:
$fh = fopen($botlog, "r");
$fil = fread($fh, filesize($botlog));
fclose($fh);
Есть куда более простая и удобная функция:
PHP:
$file = file_get_contents('./folder/file.txt');
 

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru
Если заменить на file_get_contents то выводится только одна строка и только первый знак и все :sad:
 

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru
$file = file_get_contents('./folder/file.txt');
А если в файле file.txt html теги? А не просто текст почему не выводит все что в файле?
 

Axom

Администратор
Администратор
8 Фев 2005
2.710
210
63
Пример file.txt в студию!
 

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru
Пример file.txt в студию!

просто файл html например

HTML:
<table>
<tr><td>
<b><a href="бубууб">'бубубуб'</a></b> 
текст бла блабла бубуббууббу бла
</td></tr>
</table>
Выводит только первый символ < дальше пустота
 
Последнее редактирование модератором:

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru

вот строка
PHP:
if ($file_word = file_get_contents('./modules/tema_words/quotes.txt'))
вот текст
HTML:
<a class="shakeimage" href=cvbcvb onMouseover="init(this)" onMouseout="stoprattle(this)">xcvxcv</a>
quoteeees.txt
quoteedres.txt
quotee5ees.txt
<a href=sfsdf >quote5eees.txt</a>
выводит только

HTML:
<
<

Если так то все рабоатет %)
PHP:
if ($file_word = file('./modules/tema_words/quotes.txt'))
 

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru
Есть массивы

PHP:
Array
(
    [0] => 1331123927 это ID они разные
    [1] => 4 
)
Array
(
    [0] => 1331123907 это ID они разные
    [1] => 4
)
Array
(
    [0] => 1331185208 это ID они разные
    [1] => 10
)
Нужно по [0] - ID сосчитать скока одинаковых записей есть в [1] => ??
И создать массивы с названием [1] => 4 или [1] => 10

Должно получится

PHP:
Array
(
[4] => 2 две записи с цифрой  4 в двух массивах [1] => 4 в [0] => 1331123927 и [0] => 1331123907
)
Array
(
[10] => 1 одна запись с цифрой 10 в одном массиве [1] => 10 в  [0] => 1331185208
)
 
Последнее редактирование модератором:

wext

Король пиратов
Пользователь
11 Фев 2005
3.774
22
38
34
grand line
madfrager.ru
PHP:
$array = array(
	array(19271, 4),
	array(2390, 15),
	array(723, 24),
	array(8342, 4)
);

$records = array();
foreach($array as $arr) $records[$arr[1]][] = $arr[0];
foreach($records as $num => $id)
{
	$count = count($id);
	echo $count,' записи(ь,ей) с цифрой  ',$num,' в ',$count,' массивах: ',$id[0];
	for($i=1; isset($id[$i]); $i++) echo ', ',$id[$i];
}
И в чём тут сложность? :smile:
 
  • Like
Реакции: FussesDemon

FussesDemon

Администратор
Администратор
9 Фев 2005
6.441
694
113
www.unifree.ru
А почему только одну запись пишет последнею в массиве?

PHP:
        $all_active = file("1.txt");
 
        foreach($all_active as $active)
    {
        $news_arr = explode("|", $active);
 
         $array = array(array($news_arr[6] , $news_arr[0]));  
 
} 
$records = array(); 
foreach($array as $arr) $records[$arr[1]][] = $arr[0]; 
foreach($records as $num => $id) 
{ 
    $count = count($id); 
    echo $count,' записи(ь,ей) с цифрой  ',$num,' в ',$count,' массивах: ',$id[0]; 
    for($i=1; isset($id[$i]); $i++) echo ', ',$id[$i]; 
}


PHP:
Array
(
    [0] => Array
        (
            [0] => 4
            [1] => 1331123927
        )
 
)
Array(    
    [0] => Array      (
          [0] => 4      
          [1] => 1331123907        )
)
Array(   
    [0] =>  Array        (  
          [0] => 10    
          [1] => 1331185208        )
)
 
Последнее редактирование модератором: