我们如何检查一个数组元素并在php中放入另一个数组行

时间:2016-04-13 07:51:08

标签: php arrays sorting multidimensional-array

以下是我的规则数组 在这个数组outlook中,temp。 例如,Outlook包含晴天,过度和多雨的值,也包含是或否的值。

$Rules = Array
(
[Outlook] => Array
    (
        [Sunny] => Array
            (
                [No] => 2
            )

        [Overcast ] => Array
            (
                [Yes] => 1
            )

        [Rainy] => Array
            (
                [Yes] => 1
            )

    )

[Temp] => Array
    (
        [Hot] => Array
            (
                [No] => 2
                [Yes] => 1
            )

        [Mild] => Array
            (
                [Yes] => 1
            )

    )

)

以下是我的$ filling数组,我想根据rules数组填充yes和no的值。 首先,我选择所有第一个元素行 例如我们选择outlook - >晴天,温度 - >热,然后通过标题检查上面的数组,并计算是没有值和是或否的值,然后我们分别放入游戏区域。

$filling = Array
(
[Outlook] => Array
    (

        [0] => Sunny
        [1] => Sunny
        [2] => Overcast 
        [3] => Rainy
    )

[Temp] => Array
    (

        [0] => Hot
        [1] => Hot
        [2] => Hot
        [3] => Mild
    )
 [play] => Array
    (

        [0] =>
        [1] =>
        [2] => 
        [3] => 
    )
)

示例: enter image description here

1 个答案:

答案 0 :(得分:1)

您可以通过运行online scripts

进行检查

您的数组:

$Rules = array(
    "Outlook" => array("Sunny" => array("No" => 2),
                       "Overcast" => array("Yes" => 1),
                       "Rainy" => array("Yes" => 1)
                ),
    "Temp" => array("Hot" => array("No" => 2, "Yes" => 1),
                   "Mild" => array("Yes" => 1)
                )

);

带条件的新数组

$filling = array();
$fill_play = array();

foreach($Rules as $key => $value){
    $in = 0;
    $in_play = 0;
    foreach($value as $keys => $values){
        $key_value = array_keys($values);
        for($j = 0; $j < count($key_value); $j++){
            for($i = 0; $i < $values[$key_value[$j]]; $i++){
                $fill_play[$key][$in_play++] = $key_value[$j];
                $filling[$key][$in++] = $keys;
            }
        }
    }       
}
$yes_no = array();
for($i = 0; $i < 4; $i++)
    $yes_no[$i] = 0;

foreach($fill_play as $key => $value){
    for($i = 0; $i < 4; $i++){
        if($value[$i] == 'No')
            $yes_no[$i] -= 1;
        else
            $yes_no[$i] += 1;
    }       
}

foreach($yes_no as $key => $value){
    if($value >= 0)
        $filling['Play'][$key] = 'Yes';
    else
        $filling['Play'][$key] = 'No';
}

<强>输出

echo '<pre>';
print_r($filling);
echo '</pre>';

<强>结果

Array
(
    [Outlook] => Array
        (
            [0] => Sunny
            [1] => Sunny
            [2] => Overcast
            [3] => Rainy
        )

    [Temp] => Array
        (
            [0] => Hot
            [1] => Hot
            [2] => Hot
            [3] => Mild
        )

    [Play] => Array
        (
            [0] => No
            [1] => No
            [2] => Yes
            [3] => Yes
        )

)