【问题标题】:How to sort/filter values from Array PHP?如何从 Array PHP 中排序/过滤值?
【发布时间】:2013-11-07 11:35:19
【问题描述】:

我需要foreach这个数组的值:

我的代码:

<?php

print_r(array_filter($matches));

?>

此代码的结果:

Array ( 
   [0] => Array ( 
      [0] => Age:                     // Name
      [1] => 22 Yrs.                  // Value
      [2] => Ethnicity:               // Name
      [3] => Caucasian                // Value
      [4] => Location:                // Name
      [5] => London, United Kingdom   // Value

现在我想像这样分离/过滤这些值:

$location = 'London, United Kingdom';
$age = '22 Yrs.';

所以我可以简单地做一个echo $age;

备注:在某些情况下,用户没有设置所有值。因此不能保证 Value Age 始终存在于该数组中。因此我需要类似的东西:

如果在数组中找到 "Age:" 则 $age =

我该怎么做?我在这个数组中总共有 33 个名称和 33 个值,需要根据 IF 语句对它们进行过滤,以确保该值是正确的值。

结果来自var_dump($matches);

array(1) { 
    [0]=> array(66) { 
         [0]=> string(202) " Age: " 
         [1]=> string(157) " 22 Yrs. " 
         [2]=> string(196) " Ethnicity: " 
         [3]=> string(146) " Caucasian " 
         [4]=> string(195) " Location: " 
         [5]=> string(175) " London, United Kingdom " 

结果来自var_export($matches);

array ( 
     0 => array ( 
         0 => ' Age: ', 
         1 => ' 22 Yrs. ', 
         2 => ' Ethnicity: ', 
         3 => ' Caucasian ',
         4 => ' Location: ', 
         5 => ' London, United Kingdom ',

我是新手,所以如果您有更好的方法来做到这一点,请提出建议。 感谢您的热心帮助。

【问题讨论】:

  • 你的数组看起来很奇怪
  • 更好的方法是尝试使用关联键与数值来水合数组。否则,您将陷入映射地狱,试图将键映射到特定上下文(键 0 = 年龄)。尝试水合阵列,使其看起来像:['age'] =&gt; '22 years', ['ethnicity'] =&gt; ['Caucasian'] 等...
  • 你到底是怎么弄成这样的阵列的?
  • 作为@MikePurcell,您应该匹配键=>值,这是正确且更好的方法。
  • 你可以,我认为这也是@lincb 回应所逃避的,但我强烈建议不要这样做。你可以让它在大门外工作,但维护它可能会导致一些严重的头痛。

标签: php arrays


【解决方案1】:

如上面的 cmets 所述,如果可能的话,我会尝试修改 $matches - 对于这个用例,使用关联数组会容易得多。

但是,从表面上看,您被该数据结构所困扰,这可能是一种非常幼稚的方法......

这假设您的数据将始终以[key, value, key, value, ...] 格式输出:

<?php

// original data
$matches = array(
    array(
        'Age:',
        '22 Yrs.',
        'Ethnicity:',
        'Caucasian',
        'Location:',
        'London, United Kingdom',
        'Location:',
    )
);

// chunk $matches sub-array into pairs
// we want each chunk to contain two elements,
// the first will be the key and the second will be the value
$chunks = array_chunk($matches[0], 2);

// apply a callback to each array element
$pairs = array_map(function($pair) {

    // some basic error checking...
    // if the matches subarray count is uneven for some reason

    if (count($pair) !== 2) {
        return array();
    }

    // assign each element in the pair
    list($key, $val) = $pair;


    // some basic key normalisation
    // remove non alpha chars and lowercase
    $key = strtolower($key);
    $key = preg_replace('/\W+/', '', $key);

    // return a key value pair 
    return array($key => $val);

}, $chunks);

// iterate over the pairs
// and extract into the current scope...
foreach ($pairs as $pair) {
    extract($pair);
}

// and you should now be able to echo your values
echo $age;
echo $ethnicity;
echo $location;

结果:

22 Yrs.
Caucasian
London, United Kingdom

希望这会有所帮助 :) 重申一下,我真的建议重构原始数据结构,因为上述解决方案几乎不是最优的。

【讨论】:

  • 我复制粘贴了你的代码,它工作。但是当我删除:$matches = array( array( 'Age:', '22 Yrs.', 'Ethnicity:', 'Caucasian', 'Location:', 'London, United Kingdom', 'Location:', ) ); 使用我的$matches 作为数组然后它不起作用:(你的代码非常接近我需要的。
  • 我已经更新了我的问题。我仍然无法让您的代码与我的数组 $matches 一起使用。但我看到它适用于您的阵列。你能看到我用var_dump($matches)更新的问题吗?
  • 嗯...有趣。数组应该相同。我的基础是你的文字。您可以发布您的$matches 数组进行比较吗?您是否收到错误或 WSOD?
  • 我可以看到你的阵列和我的阵列之间的区别。我的数组在所有名称和值的开头和结尾包含 white_spaces/space。请查看我的var_dump($matches); 并将其与您的var_dump($matches); 进行比较。
  • 这应该没关系 - 我已经允许了。 $key = preg_replace('/\W+/', '', $key); 行从字符串中删除所有非字母字符,然后将其分配给$key。因此," Age: " 变为 'Age',以此类推。所以最终的结果应该是一样的。使用自己的数组运行时是否出现错误或空白屏幕,或者输出是什么?
【解决方案2】:

此答案假定您正在使用直接包含数据的数组,这与显示 3 个嵌套数组的输出示例不同。

for($i=0; $i<(count($matches)/2); $i++){
 $label = substr($matches[$i*2],0,-1);
 $output[$label] = $matches[$i*2+1];
}

这将使 $output 成为一个关联数组,可以像这样寻址:

echo($output["Age"]);

不幸的是,据我所知,将其转化为单个变量是不可能的。

【讨论】:

    【解决方案3】:

    尝试单独使用数组可能更容易,例如。

    $Age = Array ( 
        [0] => 22,
        [1] => 33
    );
    
    $Ethnicity = Array ( 
        [0] => "Caucasian",
        [1] => "Other"
    );
    
    $Location= Array ( 
        [0] => "London, United Kingdom",
        [1] => "Germany"
    );
    

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 2016-01-16
      • 2015-12-19
      • 2021-07-03
      • 1970-01-01
      • 2021-03-31
      • 2010-10-13
      • 2018-12-08
      • 1970-01-01
      相关资源
      最近更新 更多