即使缺少一个值,也要编写好的句子

时间:2014-06-03 13:50:29

标签: php

我真的厌倦了制作" if elseifif"陈述你知道一个有趣的方法来解决这个问题:

为了这个例子的目的,我将重点关注3个变量,但实际上有超过500个。

必填变量:

名称

这些变量可以为空:

生日,城市

我想写一个这样的句子:

35岁的用户John Doe离开匹兹堡。

但如果生日是空的,我想写:

用户John Doe离开匹兹堡。

依旧......

您可以在此处查看预期输出和实际值数组: http://jsfiddle.net/CMC8a/1/

我尝试了多种方法来解决此问题,请点击此处了解更多信息:

<style>
    *{
        font-family: Helvetica;
    }
    label{
        font-size: large;
    }

</style>
<table id="entete">

</table>
<h2><?php echo $data['patient']['nom']['value'] ?> <?php echo $data['patient']['prenom']['value'] ?> <?php echo age_count($data['patient']['ddn']['value']) ?> ans</h2>


<?php
$blocInfoGenerales = new BlocColumnPdf(
        'Informations générales', array(
    $data['patient']['ddn'],
    $data['patient']['sexe'],
    $data['patient']['profession'],
    $data['patient']['villeNaissance']
    , $data['patient']['departement'])
        , 2
);
$blocInfoGenerales->render();
?>
<h3>Antécédents personnels</h3>
<table>
    <tr>
        <td><label>Respiratoires : </label><?php echo makeCommaForThoseMCB(array($data['N1']['asthme'], $data['N1']['rhinite'], $data['N1']['bcpo'], $data['N1']['insuffisanceResp'], $data['N1']['chirurgieOrl'], $data['N1']['autreChirurgie'], $data['N1']['allergies'], $data['N1']['old'])) ?></td>
    </tr>
    <tr>
        <td><label>Cardio-vasculaires et cérébraux : </label><?php echo makeCommaForThoseMCB(array($data['N1']['hypertensionArterielle'], $data['N1']['infarctusMyocarde'], $data['N1']['bcpo'], $data['N1']['insuffisanceCoronaire'], $data['N1']['troubleRythme'], $data['N1']['accidentVasculaireCerebral'], $data['N1']['insuffisanceCardiaque'], $data['N1']['arteriopathie'])) ?></td>
    </tr>
    <tr>
        <td><label>Autres : </label><?php echo makeCommaForThoseMCB(array($data['N1']['tabagismeActuel'], $data['N1']['tabagismeAncien'], $data['N1']['alcool'], $data['N1']['refluxGastro'], $data['N1']['glaucome'], $data['N1']['diabete'], $data['N1']['hypercholesterolemie'], $data['N1']['hypertriglyceridemie'], $data['N1']['dysthyroidie'], $data['N1']['depression'])) ?></td>
    </tr>
    <tr>
        <td><label>Antécédents familiaux : </label><?php echo makeCommaForThoseMCB(array($data['N1']['sedentarite'], $data['N1']['syndromeDApneesSommeil'], $data['N1']['obesite'], $data['N1']['dysmorphieFaciale'])) ?></td>
    </tr>
</table>
<h3>Traitements en cours</h3>
<table>
    <tr>
        <td><?php echo makeCommaforThisVMB($data['N1']['vidalMultiBox'], 'vidalMultiBox') ?></td>
    </tr>

</table>
<h3>Première visite</h3>
<table>
    <tr>
        <td>
            <?php echo makeCommaForThoseFields(array($data['suivi1'][0]['dateVisite'], $data['suivi1'][0]['adressePar'], $data['suivi1'][0]['selecMedecinSpecialiste'])) ?>
        </td>
    </tr>
    <tr>
        <td>
            <?php echo makeCommaForThoseFields(array($data['suivi1'][0]['motifConsultation'])) ?>
        </td>
    </tr>
    <tr>
        <td>
            <?php echo makeCommaForThoseFields(array($data['suivi1'][0]['taille'], $data['suivi1'][0]['poids'], $data['suivi1'][0]['perimetreCervical'], $data['suivi1'][0]['perimetreAbdominal'])) ?>
        </td>
    </tr>
    <tr>
        <td>
            <?php echo makeCommaForThoseFields(array($data['suivi1'][0]['PASystolique'], $data['suivi1'][0]['PADiastolique'])) ?>
        </td>
    </tr>
    <tr>
        <td><label> <?php echo makeCommaForThoseMCB(array($data['suivi1'][0]['profilMaxilofacial'])) ?></label></td>
    </tr>
    <tr>
        <td>
            <?php echo makeCommaForThoseFields(array($data['suivi1'][0]['autoPASystolique'], $data['suivi1'][0]['autoPADiastolique'])) ?>
        </td>
    </tr>
    <tr>
        <td>
            <label>Bilan Biologique :</label>
            <?php
            echo makeCommaForThoseFields(array(
                $data['suivi1'][0]['dateBilan'], $data['suivi1'][0]['glycemie'],
                $data['suivi1'][0]['cholesterolemieTotale'], $data['suivi1'][0]['HDL'],
                $data['suivi1'][0]['LDL'], $data['suivi1'][0]['triglycerides']
            ))
            ?>
        </td>
    </tr>
    <tr>
        <td><label>Clinique :</label> <?php
            echo makeCommaForThoseMCB(
                    array(
                        $data['suivi1'][0]['ronflements'],
                        $data['suivi1'][0]['somnolenceDiurne'],
                        $data['suivi1'][0]['somnolenceConduite'],
                        $data['suivi1'][0]['fatigueMatinale'],
                        $data['suivi1'][0]['cephaleesMatinales'],
                        $data['suivi1'][0]['troubleLibido'],
                        $data['suivi1'][0]['troubleMemoire'],
                        $data['suivi1'][0]['troubleErection'],
                        $data['suivi1'][0]['transpirationNocturne']
            ))
            ?>
        </td>

    </tr>
    <tr>
         <td><label>Auto-questionnaires :</label> <?php
            echo makeCommaForThoseFields(
                    array(
                        $data['suivi1'][0]['echelleEpworth'],
                        $data['suivi1'][0]['echellePichot'],
                        $data['suivi1'][0]['echelleDepression'],
                        $data['suivi1'][0]['SJSRCriteresDiagnostiques']
            ))
            ?>
        </td>
    </tr>
    <tr>
        <?php $data['suivi1'][0]['estimationDureeMoyenneDeSommeil']['label'] = 'Estimation durée moyenne de sommeil' ?>
         <td><?php echo makeCommaForThoseFields(array($data['suivi1'][0]['estimationDureeMoyenneDeSommeil']     )) ?></td>
    </tr>
    <tr>
         <td>
            <label>Exploration fonctionnelle respiratoire :</label>
            <?php
            echo makeCommaForThoseFields(array(
                $data['suivi1'][0]['dateBilan'], $data['suivi1'][0]['glycemie'],
                $data['suivi1'][0]['cholesterolemieTotale'], $data['suivi1'][0]['HDL'],
                $data['suivi1'][0]['LDL'], $data['suivi1'][0]['triglycerides']
            ))
            ?>
        </td>
    </tr>

</table>


<?php

function count_capitals($s) {
    return strlen(preg_replace('![^A-Z]+!', '', $s));
}

function custom_strtolower($string) {
    if (count_capitals($string) <= 1) {
        return strtolower($string);
    }
    return $string;
}

function makeCommaForThoseFields($elements) {
    $i = 0;
    $response = false;
    foreach ($elements as $element) {
        if ($element['value']) {
            if ($i == 0) {
                $response = '<label>' . $element['label'] . '</label> : ';
                $response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
                $response .= (isset($element['unit'])&& $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
            } else {
                if ($element['label'] != 'Préciser' && $element['label'] != 'Préciser') {
                    $response .= ', <label>' . custom_strtolower($element['label']) . '</label> : ';
                    $response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
                    $response .= (isset($element['unit'])&& $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
                } else {
                    $response .= ' (';
                    $response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
                    $response .= (isset($element['unit']) && $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
                    $response .= ')';
                }
            }
            $i++;
        }
    }
    if ($response) {
        $response.='.';
    }
    return $response;
}

function makeCommaforThisVMB($vidalMultiBox, $key) {
    $i = 0;
    $response = false;
    foreach ($vidalMultiBox as $element) {
        $response = $element[$key . '_libelle'] . ' ' . $element[$key . '_val_posologie'] . ' ' . $element[$key . '_id_posologie'] . ', ';
    }

    if ($response) {
        $response = substr($response, 0, -2);
        $response.='.';
    }
    return $response;
}

function makeCommaForThoseMCB($elements) {
    $i = 0;
    $response = false;
    foreach ($elements as $element) {
        if ($element['value'] == 1) {

            if ($i == 0) {
                $response = $element['label'];
            } else {
                $response.= ', ' . strtolower($element['label']);
            }
            $i++;
        }
    }
    if ($response) {
        $response.='.';
    }
    return $response;
}

class BlocColumnPdf {

    private $m_title;
    private $elements;
    private $m_colone;
    private $m_id;

    function __construct($title, $p_elements, $p_colone, $id) {
        $this->m_title = $title;
        foreach ($p_elements as $e) {
            $tmp_e = new ElementColumnPdf($e);
            if (!$tmp_e->isEmpty()) {
                $this->elements[] = $tmp_e;
            }
        }

        $this->m_colone = $p_colone;
        return $this;
    }

    function render() {
        $is_empty = true;
        foreach ($this->elements as $e) {
            if (!$e->isEmpty()) {
                $is_empty = false;
                break;
            }
        }
        if (!$is_empty) {
            echo '<h3>' . $this->m_title . '</h3>';
            echo '<table id="' . $this->m_id . '">';
            $lines_elements = array_chunk($this->elements, $this->m_colone);
            foreach ($lines_elements as $line_elements) {
                $this->renderLine($line_elements);
            }

            echo '</table>';
        }
    }

    function renderLine($elements) {
        foreach ($elements as $e) {
            if (!$e->isEmpty()) {
                $is_empty = false;
                break;
            }
        }
        if (!$is_empty) {
            echo '<tr>';
            foreach ($elements as $e) {
                $e->render();
            }
            echo '</tr>';
        }
    }

}

class ElementColumnPdf {

    private $element;

    function __construct($p_element) {
        $this->element = $p_element;
        return $this;
    }

    function render() {
        $text = (isset($this->element['libelle']) && $this->element['libelle']) ? $this->element['libelle'] : $this->element['value'];
        $unit = (isset($this->element['unit']) && $this->element['unit']) ? $this->element['unit'] : '';
        if (!$this->isEmpty()) {
            echo '<td><label>' . $this->element['label'] . '</label> <span class="value">' . $text . '</span><span class="unit">' . $unit . '</span></td>';
        } else {
            echo '<td></td>';
        }
    }

    function isEmpty() {
        if ($this->element['value']) {
            return false;
        }
        return true;
    }

}

使用和滥用是因为我使用的工具将HTML转换为PDF。这个工具用table而不是div做得更好

你会做什么?

1 个答案:

答案 0 :(得分:2)

这实际上是一个有趣的问题。

理想情况下,你需要做的是创建一系列关于这个人的“事物”,然后制作一个人类可读的事实清单。

这样的事情可以很好地运作:

$things = array();
if( !empty($birthdate)) $things[] = "who is aged ".$birthdate;
if( !empty($city)) $things[] = "lives in ".$city;

然后输出:

echo "The user ".$name;
if( $things) { // check that there are actually things to say
    $lastthing = array_pop($things);
    if( $things) { // see if there are still things, ie. there were at least two
        echo implode(", ",$things);
        echo " and ";
    }
    echo $lastthing;
}

根据项目数量,上述结构会产生语法正确的列表:

  1. A
  2. A和B
  3. A,B和C
  4. A,B,C和D
    [等等]