С Новым годом! Форум программистов, компьютерный форум, киберфорум
PHP
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.83/18: Рейтинг темы: голосов - 18, средняя оценка - 4.83
0 / 0 / 0
Регистрация: 11.10.2014
Сообщений: 15

Как сделать вывод разных данных в зависимости от значения переменной

23.02.2015, 20:54. Показов 3422. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте. Вообщем у меня есть рабочий скрипт, который получает ответ от сервера и выводит всегда цену. А мне надо сделать что бы если товара нет, то выводило соответствующее сообщение.

Нашел что все это дело кроется тут

PHP
1
2
3
4
5
6
7
8
9
10
11
12
    $result .= "<div class=\"detals\" id=\"fragment-1\">
        <ul class=\"products\">
        <div class=\"item-loop\">
        <span class=\"digiseller-vitrinaicon $html_class_name\">$vitrina_icon</span>
        <div class=\"coast\">".$product -> price." ".$curr_name."</div>
                            
        <div class=\"name\"><a href=\"./goods_info.php?id=".$product -> id."\">".$product -> name."</a></div>
        <div class=\"poster\"><a href=\"./goods_info.php?id=".$product -> id."\" alt=".$product -> name.">$img</a></div>
        </div>
            
        </ul>
</div>\n";}}}
В ответе есть некоторая переменная .$product -> in_stock. которая возвращает 0 когда товара нет. Что попробывал сделать я.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$result .= "<div class=\"detals\" id=\"fragment-1\">
        <ul class=\"products\">
        <div class=\"item-loop\">
        <span class=\"digiseller-vitrinaicon $html_class_name\">$vitrina_icon</span>"
 
            $worlds = 'Нет в наличии';
                if (.$product -> in_stock == 0) 
                    { $worlds = 'Нет в наличии'; }
                else { $worlds = .$product -> price." ".$curr_name.; }
                            
        "<div class=\coast\">" $worlds"</div>
        <div class=\"name\"><a href=\"./goods_info.php?id=".$product -> id."\">".$product -> name."</a></div>
        <div class=\"poster\"><a href=\"./goods_info.php?id=".$product -> id."\" alt=".$product -> name.">$img</a></div>
        </div>
            
        </ul>
</div>\n";}}}
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
23.02.2015, 20:54
Ответы с готовыми решениями:

Картинка в зависимости от значения переменной - как сделать?
День добрый. Подскажите, как выводить картинку в Image в зависимости от значения переменной. Допустим жму кнопку, и если значение одно, то...

Веб. Как сделать подсветку ячейки в зависимости от значения переменной?
Доброго времени суток, подскажите пожалуйста, как подсветить ячейку таблицы в зависимости от переменной $i (php)?? Нужно сделать что бы...

Как в зависимости от значения переменной сделать кнопку активной или неактивной?
Как в зависимости от значения переменной сделать кнопку активной или неактивной?

4
31 / 31 / 15
Регистрация: 02.02.2015
Сообщений: 152
23.02.2015, 21:00
Lesha, может так лучше?
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$worlds = 'Нет в наличии';
if ($product -> in_stock > 0) {
    $worlds = $product -> price." ".$curr_name.;
}
$result .= "<div class=\"detals\" id=\"fragment-1\">
        <ul class=\"products\">
        <div class=\"item-loop\">
        <span class=\"digiseller-vitrinaicon $html_class_name\">$vitrina_icon</span>
        <div class=\coast\">" . $worlds . "</div>
 
        <div class=\"name\"><a href=\"./goods_info.php?id=".$product -> id."\">".$product -> name."</a></div>
        <div class=\"poster\"><a href=\"./goods_info.php?id=".$product -> id."\" alt=".$product -> name.">$img</a></div>
        </div>
            
        </ul>
</div>\n";}}}
0
0 / 0 / 0
Регистрация: 11.10.2014
Сообщений: 15
23.02.2015, 21:06  [ТС]
wmaster575, не, не помогает. Все равно показывает пустую страницу.

Добавлено через 2 минуты
Код всей страницы, мало ли

Кликните здесь для просмотра всего текста
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<?php
require_once "./inc/functions.php";
 
$tmp_type = "php";
$tmp_file = "0.tmp";
?>
<?php
// заголовок страницы, ID продавца и пр. параметры
$head["title"] = "****";
$GLOBALS["default_gl"] = $default_gl;
$GLOBALS["default_order"] = $default_order;
$GLOBALS["tmp_dir"] = $tmp_dir;
$GLOBALS["category_img_size"] = $main["category_img_size"];
$GLOBALS["goods_img_size"] = $main["goods_img_size"];
// установленная страница(по умолчанию - 1)
get_current_page();
// количество строк и количество страниц
$GLOBALS["rows"] = $default_rows;
$GLOBALS["count_page"] = $main["pages"];
 
// определение типа валюты
show_other_name_rate();
// определиние порядка сортировки
    if(isset($_SESSION["order"]) and !empty($_SESSION["order"])){
        switch($_SESSION["order"]){
            case "name":
            $order = "name";
            break;
        
            case "nameDESC":
            $order = "nameDESC";
            break;
        
            case "price":
            $order = "price";
            break;
        
            case "priceDESC":
            $order = "priceDESC";
            break;
        
            default:
            $order = "name";}}
    else{
        if(isset($GLOBALS["default_order"]) and !empty($GLOBALS["default_order"])){
            switch($GLOBALS["default_order"]){
                case "name":
                $order = "name";
                break;
        
                case "nameDESC":
                $order = "nameDESC";
                break;
        
                case "price":
                $order = "price";
                break;
        
                case "priceDESC":
                $order = "priceDESC";
                break;
        
                default:
                $order = "name";}}}
$GLOBALS["order"] = $order;
 
// функция вывода контента
function show_content(){
    $result = "";
    
    // определение ID группы товаров
    if(isset($_GET["category_id"]) && !empty($_GET["category_id"])){
    $_GET["category_id"] = abs((int)$_GET["category_id"]);
        if(!empty($_GET["category_id"])){
        $answer = $GLOBALS["obj"] -> parse_xml($GLOBALS["obj"] -> goods_list($GLOBALS["seller_id"],$_GET["category_id"],$_REQUEST["page"],$GLOBALS["rows"],$GLOBALS["curr_name"],$GLOBALS["order"]));}
        else {$answer = $GLOBALS["obj"] -> parse_xml($GLOBALS["obj"] -> goods_list($GLOBALS["seller_id"],$GLOBALS["default_gl"],$_REQUEST["page"],$GLOBALS["rows"],$GLOBALS["curr_name"],$GLOBALS["order"]));}}
    else{$answer = $GLOBALS["obj"] -> parse_xml($GLOBALS["obj"] -> goods_list($GLOBALS["seller_id"],$GLOBALS["default_gl"],$_REQUEST["page"],$GLOBALS["rows"],$GLOBALS["curr_name"],$GLOBALS["order"]));}
 
    if($answer -> retval != 0){
    $result .= "<p>".$answer -> retdesc."</p>\n";
    echo $answer -> retdesc;}
    else{
        if(isset($answer -> subcategories -> subcategory)){
        }
    $result .= "<!-- Список товаров -->\n<div class=\"digiseller-productList digiseller-homepage\">\n";
 
        if($answer -> products["cnt"] > 0){
            if($_REQUEST["page"] > $answer -> pages["cnt"]){
            $result .= "<p>".$GLOBALS["mess"]["page_not_found"]."</p>\n";}
            else{
                foreach($answer -> products -> product as $product){
                $img = "<img src=\"http://graph.digiseller.ru/img.ashx?id_d=".$product -> id."".$GLOBALS["goods_img_size"]."\"  />\n";
                    switch($product["icon"]){
                        case "new":
                        $html_class_name = " digiseller-newproduct";
                        $vitrina_icon = "Новинка!";
                        break;
                        
                        case "sale":
                        $html_class_name = " digiseller-action";
                        $vitrina_icon = "Акция!";
                        break;
                        
                        case "top":
                        $html_class_name = " digiseller-lider";
                        $vitrina_icon = "Лидер продаж!";
                        break;
                        
                        default:
                        $html_class_name = "";
                        $vitrina_icon = "&nbsp;";}
                        
                        $curr_name = $answer -> products -> currency;
                        $self_url = urlencode("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);
                        
                        
$worlds = 'Нет в наличии';
if ($product -> in_stock > 0) {
    $worlds = $product -> price." ".$curr_name.;
}
 
$result .= "<div class=\"detals\" id=\"fragment-1\">
        <ul class=\"products\">
        <div class=\"item-loop\">
        <span class=\"digiseller-vitrinaicon $html_class_name\">$vitrina_icon</span>
        <div class=\coast\">" . $worlds . "</div>
 
        <div class=\"name\"><a href=\"./goods_info.php?id=".$product -> id."\">".$product -> name."</a></div>
        <div class=\"poster\"><a href=\"./goods_info.php?id=".$product -> id."\" alt=".$product -> name.">$img</a></div>
        </div>
            
        </ul>
</div>\n";}}}
                    
                    include 'box.php'; 
    $result .= "<div class=\"digiseller-both\"></div>\n</div>\n<!-- end.Список товаров -->
    <div id=\"digiseller-loader\" class=\"digiseller-loader\" style=\"display: none;\">Загрузка...</div>\n";
    echo $result;}
?>
         
<?php }
// функция шаблонизации
tmp_open($tmp_type,$tmp_dir,$tmp_file,$head);
?>
0
433 / 352 / 259
Регистрация: 29.11.2011
Сообщений: 628
23.02.2015, 21:27
Лучший ответ Сообщение было отмечено Lesha как решение

Решение

Вот:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
<?php
require_once "./inc/functions.php";
 
$tmp_type = "php";
$tmp_file = "0.tmp";
?>
<?php
// заголовок страницы, ID продавца и пр. параметры
$head["title"] = "****";
$GLOBALS["default_gl"] = $default_gl;
$GLOBALS["default_order"] = $default_order;
$GLOBALS["tmp_dir"] = $tmp_dir;
$GLOBALS["category_img_size"] = $main["category_img_size"];
$GLOBALS["goods_img_size"] = $main["goods_img_size"];
// установленная страница(по умолчанию - 1)
get_current_page();
// количество строк и количество страниц
$GLOBALS["rows"] = $default_rows;
$GLOBALS["count_page"] = $main["pages"];
 
// определение типа валюты
show_other_name_rate();
// определиние порядка сортировки
if(isset($_SESSION["order"]) and !empty($_SESSION["order"])){
    switch($_SESSION["order"]){
        case "name":
            $order = "name";
            break;
 
        case "nameDESC":
            $order = "nameDESC";
            break;
 
        case "price":
            $order = "price";
            break;
 
        case "priceDESC":
            $order = "priceDESC";
            break;
 
        default:
            $order = "name";
    }
}
else{
    if(isset($GLOBALS["default_order"]) and !empty($GLOBALS["default_order"])){
        switch($GLOBALS["default_order"]){
            case "name":
                $order = "name";
                break;
 
            case "nameDESC":
                $order = "nameDESC";
                break;
 
            case "price":
                $order = "price";
                break;
 
            case "priceDESC":
                $order = "priceDESC";
                break;
 
            default:
                $order = "name";
        }
    }
}
$GLOBALS["order"] = $order;
 
// функция вывода контента
function show_content()
{
    $result = "";
 
    // определение ID группы товаров
    if(isset($_GET["category_id"]) && !empty($_GET["category_id"])) {
        $_GET["category_id"] = abs((int)$_GET["category_id"]);
        if(!empty($_GET["category_id"])) {
            $answer = $GLOBALS["obj"] -> parse_xml($GLOBALS["obj"] -> goods_list($GLOBALS["seller_id"],$_GET["category_id"],$_REQUEST["page"],$GLOBALS["rows"],$GLOBALS["curr_name"],$GLOBALS["order"]));
        }
        else {
            $answer = $GLOBALS["obj"] -> parse_xml($GLOBALS["obj"] -> goods_list($GLOBALS["seller_id"],$GLOBALS["default_gl"],$_REQUEST["page"],$GLOBALS["rows"],$GLOBALS["curr_name"],$GLOBALS["order"]));
        }
    }
    else
    {
        $answer = $GLOBALS["obj"] -> parse_xml($GLOBALS["obj"] -> goods_list($GLOBALS["seller_id"],$GLOBALS["default_gl"],$_REQUEST["page"],$GLOBALS["rows"],$GLOBALS["curr_name"],$GLOBALS["order"]));
    }
 
    if($answer -> retval != 0) {
        $result .= "<p>".$answer -> retdesc."</p>\n";
        echo $answer -> retdesc;
    }
    else
    {
        if(isset($answer -> subcategories -> subcategory)) { }
        $result .= "<!-- Список товаров -->\n<div class=\"digiseller-productList digiseller-homepage\">\n";
 
        if($answer -> products["cnt"] > 0){
            if($_REQUEST["page"] > $answer -> pages["cnt"]){
                $result .= "<p>".$GLOBALS["mess"]["page_not_found"]."</p>\n";}
            else{
                foreach($answer -> products -> product as $product){
                    $img = "<img src=\"http://graph.digiseller.ru/img.ashx?id_d=".$product -> id."".$GLOBALS["goods_img_size"]."\"  />\n";
                    switch($product["icon"]){
                        case "new":
                            $html_class_name = " digiseller-newproduct";
                            $vitrina_icon = "Новинка!";
                            break;
 
                        case "sale":
                            $html_class_name = " digiseller-action";
                            $vitrina_icon = "Акция!";
                            break;
 
                        case "top":
                            $html_class_name = " digiseller-lider";
                            $vitrina_icon = "Лидер продаж!";
                            break;
 
                        default:
                            $html_class_name = "";
                            $vitrina_icon = "&nbsp;";}
 
                    $curr_name = $answer -> products -> currency;
                    $self_url = urlencode("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);
 
 
                    $worlds = ($product -> in_stock > 0) ? $product -> price."&nbsp;".$curr_name : 'Нет в наличии';
 
                    $result .= "<div class=\"detals\" id=\"fragment-1\">
                                <ul class=\"products\">
                                <div class=\"item-loop\">
                                <span class=\"digiseller-vitrinaicon $html_class_name\">$vitrina_icon</span>
                                <div class=\"coast\">" . $worlds . "</div>
 
                                <div class=\"name\"><a href=\"./goods_info.php?id=".$product -> id."\">".$product -> name."</a></div>
                                <div class=\"poster\"><a href=\"./goods_info.php?id=".$product -> id."\" alt=".$product -> name.">$img</a></div>
                                </div>
 
                                </ul>
                                </div>\n";
                }
            }
        }
 
        include 'box.php';
        $result .= "<div class=\"digiseller-both\"></div>\n</div>\n<!-- end.Список товаров -->
                    <div id=\"digiseller-loader\" class=\"digiseller-loader\" style=\"display: none;\">Загрузка...</div>\n";
        echo $result;
    }
}
// функция шаблонизации
tmp_open($tmp_type,$tmp_dir,$tmp_file,$head);
?>
Добавлено через 6 минут
Если некорректно работает, скопируйте код еще раз, я немного изменил.
1
Эксперт PHP
 Аватар для Fedor Vlasenko
936 / 693 / 236
Регистрация: 01.02.2015
Сообщений: 1,848
23.02.2015, 23:31
перепишите $GLOBALS не позорьтесь
Lesha, не надоело кавычки экранировать
PHP
1
2
3
4
5
6
$b = 2; $c = 3;
$a = <<<TEXT
$b "Тестим"
$c Прверяем "еще"
TEXT;
echo $a;
Песочница
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
23.02.2015, 23:31
Помогаю со студенческими работами здесь

Как сделать так чтобы PyQt периодически обновлял текст, в зависимости от изменения значения переменной
Есть код на PyQt5, хочу сделать так, чтобы в строке постоянно выводилось значение переменной, периодически обновляясь в зависимости от...

Вывод разных данных в зависимости от сессии
Нужно, чтобы если пользователь залогинен, то выводилось &quot;Выйти&quot;, а если он не залогинен, выводилась форма логина. Все это должно быть на...

Вывод значения в зависимости от того какая цифра в переменной
Привет, как мне сделать такое есть переменная $sex она возвращает числовое значение пола 1-женский, 2-мужской, 3-неопределен мне...

Вывод значения в зависимости от того есть данные в переменной
Привет, как мне записать правильно условие если переменная $title пустая сейчас выводит переменная пустая! нужно такое же только...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и источниками (напряжения, ЭДС и тока). Найти токи и напряжения во всех элементах. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru