PHP - 根据数组内的值选择数组

时间:2014-08-05 01:46:53

标签: php arrays multidimensional-array

我希望能够在不使用数字位置的情况下选择数组中的特定数组。我不想使用数字位置的原因是因为根据登录的用户,位置并不总是相等。

例如,使用以下数组,我只想选择x值为YourPhone的数组。

数组结构:

$salesArray = array(
    array(
        'key' => 'Basic Planners',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 150),
            array('x' => 'Universe X3', 'y' => 300),
            array('x' => 'ePhone 74s', 'y' => 1500),
            array('x' => 'NextUs', 'y' => 50),
            array('x' => 'Humanoid', 'y' => 500)
        )
    ),
    array(
        'key' => 'No-Namers',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 300),
            array('x' => 'Universe X3', 'y' => 250),
            array('x' => 'ePhone 74s', 'y' => 400),
            array('x' => 'NextUs', 'y' => 150),
            array('x' => 'Humanoid', 'y' => 900)
        )
    ),
    array(
        'key' => 'Feature Followers',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 359),
            array('x' => 'Universe X3', 'y' => 900),
            array('x' => 'ePhone 74s', 'y' => 100),
            array('x' => 'NextUs', 'y' => 500),
            array('x' => 'Humanoid', 'y' => 250)
        )
    ),
    array(
        'key' => 'Hipsters & Elites',
        'values' => array(
            array('x' => 'YourPhone', 'y' => 200),
            array('x' => 'Universe X3', 'y' => 350),
            array('x' => 'ePhone 74s', 'y' => 50),
            array('x' => 'NextUs', 'y' => 800),
            array('x' => 'Humanoid', 'y' => 100)
        )
    )
  );

现在我正在选择这样的值:

<?php $currentTeam = 0; ?>

 <table>
   <?php foreach ($sales as $sale) { ?>
     <tr>
       <td><?php echo $sale['key']; ?></td>
       <td><?php echo $sale['values'][$currentTeam]['y']; ?></td>
     </tr>
   <?php } ?>
 </table>

2 个答案:

答案 0 :(得分:1)

此代码块解决了它:

<强>改性

$currentTeam = "YourPhone"; ?>

 <table>
   <?php foreach ($salesArray as $sale) { ?>

     <tr>
       <td><?php echo $sale['key']; ?></td>
       <td><?php
            foreach($sale['values'] as $values){
                if($values['x'] == $currentTeam )
                    echo $values['y'];
            }

        ?>
        </td>
     </tr>
   <?php } ?>
 </table>

你需要使用另一个foreach来完全控制下一个数组。

答案 1 :(得分:1)

由于您只需要该特定密钥,只需使用if条件进行检查,如果匹配则再进行打印。像这样:Example

<?php $needle = 'YourPhone'; ?>
<table>
    <?php foreach ($salesArray as $sale) { ?>
        <?php
        $key = null;
        foreach($sale['values'] as $index => $info) {
            if($info['x'] == $needle) {
            // if(stripos($info['x'], $needle) !== false) {
                $key = $index;
                break;
            }
        }
        ?>
        <tr>
           <td><?php echo $sale['key']; ?></td>
           <td><?php echo $sale['values'][$key]['y']; ?></td>
        </tr>
    <?php } ?>
</table>