简体   繁体   English

如何在javascript中检查php数组的长度

[英]how to check the length of the php array in javascript

I have two div 1st div contains some value and second div has the 我有两个div第一个div包含一些值,第二个div包含
php array which is fetching from the backend. 从后端获取的php数组。 i want to check on page load that if the array is empty or it contains some value using the javascript. 我想检查页面加载是否数组为空或它包含一些使用javascript的值。 if it contains the value i should minimize the 1st div else it should expand. 如果它包含值i,则应最小化第一个div,否则应扩展。 code: 码:

<div class="firstdiv ">
  <div >
    <p class="jb_text"><?php echo $per->name;?></p><hr>
  </div>
</div>

<div class="seconddiv ">
    <div class="panel-group" >
      <?php if($data): ?>
        <?php foreach($data as $work): ?>
          <div class="panel panel-default" id = "transp">
           <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 cd-name text-capitalize"><?php echo $work->first_name." ".$work->last_name; ?>
           </div>   
          </div> 
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
</div>

how to check the length of the php array in javascript. 如何在javascript中检查php数组的长度。

You can't "count the php array with javascript". 您不能“使用javascript计数php数组”。 Php is server side, javascript is client side. PHP是服务器端,javascript是客户端。 That being said, you can count the displayed element by the php foreach . 话虽如此,您可以通过php foreach计算显示的元素。

To do so, with Jquery you can go with : 为此,使用Jquery可以使用:

if(!$('.panel panel-default').length) {
    $('.seconddiv').hide();
}

in browser you need to count the div or element by class in this case 在这种情况下,您需要在浏览器中按class计算div或元素

<script>
seconddivLength = document.querySelectorAll(".panel.panel-default").length;
alert("seconddiv Length is: " + seconddivLength)
</script>

You can't count a PHP array with Javascript. 您无法使用Javascript计算PHP数组。

Try something like this though. 尝试这样的事情。

   <div class="firstdiv ">
      <div >
        <p class="jb_text"><?php echo $per->name;?></p><hr>
      </div>
    </div>

    <div class="seconddiv ">
        <div class="panel-group" >
          <?php if(isset($data) && is_array($data) && count($data) >= 1): ?>
            <?php foreach($data as $work): ?>
              <div class="panel panel-default" id = "transp">
               <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 cd-name text- 
   capitalize"><?php echo $work->first_name." ".$work->last_name; ?>
               </div>   
              </div> 
            <?php endforeach; ?>
          <?php else: ?>
            <!-- What ever else you want if its empty -->
          <?php endif; ?>
        </div>
    </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM