比较字符串和数组值

时间:2013-01-16 08:52:12

标签: php arrays string

例如我们有字符串

$somestring = '11;11;11;12;13';

和数组

    $somearray = array(
  11 => array(
    prop => array(0=>11),
    uid => 1,
  ),
  21 => array(
    prop => array(0=>12),
    uid => 2,
  ),
  32 => array(
    prop => array(0=>11),
    uid => 1,
  ),  
  34 => array(
    prop => array(0=>11),
    uid => 2,
  ),  
 35 => array(
    prop => array(0=>13),
    uid => 1,
  ),  
  36 => array(
    prop => array(0=>13),
    uid => 3,
  ),  
  37 => array(
    prop => array(0=>12),
    uid => 1,
  ),  
  38 => array(
    prop => array(0=>12),
    uid => 3,
  ),  
  39 => array(
    prop => array(0=>12),
    uid => 1,
  ),
);

如果在$ somestring中[prop]的值等于相同的值,则从$ somearray [uid]获取并输出它,如下所示:

row1:11(uid:1);11(uid:1);11(uid:2);12(uid:2);13(uid:1)
row2:11(uid:);11(uid:);11(uid:);12(uid:1);13(uid:3)
row3:11(uid:);11(uid:);11(uid:);12(uid:3);13(uid:)
row4:11(uid:);11(uid:);11(uid:);12(uid:1);13(uid:)

我在http://eval.in/6816找到了一个相关的解决方案,但它没有处理重复的值

2 个答案:

答案 0 :(得分:2)

只需复制并执行,

<?php
error_reporting(0);
$somestring = '11;11;11;12;13';

$somearray = array(
  11 => array(
    prop => array(0=>11),
    uid => 1,
  ),
  21 => array(
    prop => array(0=>12),
    uid => 2,
  ),
  32 => array(
    prop => array(0=>11),
    uid => 1,
  ),  
  34 => array(
    prop => array(0=>11),
    uid => 2,
  ),  
 35 => array(
    prop => array(0=>13),
    uid => 1,
  ),  
  36 => array(
    prop => array(0=>13),
    uid => 3,
  ),  
  37 => array(
    prop => array(0=>12),
    uid => 1,
  ),  
  38 => array(
    prop => array(0=>12),
    uid => 3,
  ),  
  39 => array(
    prop => array(0=>12),
    uid => 1,
  ),
);

$sme_array    = explode(";",$somestring);
$somestrarray = array_unique($sme_array);
$res          = array();
foreach($somearray as $key=>$val){

    foreach($somestrarray as $value){
        if($val['prop'][0] == $value){
           $res[$value][]   = $val['uid'];
        }       
    }
}

$cnt_values  = array_count_values($somestrarray);

$num_loop    = 1;
foreach($cnt_values as $key=>$val){
  $num_loop  = (count($res[$key])/$val) > $num_loop?(count($res[$key])/$val):$num_loop;
}

for($i=0; $i<$num_loop; $i++){
    echo "row".($i+1).":";
    foreach($sme_array as $vals){
      if(array_key_exists($vals,$res)){
      echo $vals."(uid:".$res[$vals][0].");";
      array_shift($res[$vals]);
      }
    }
    echo "<br>";
}


?>

答案 1 :(得分:0)

<?php

$str_array=explode(';',$somestring);
$final=array();

foreach($str_array as $key => $value1)
{
 foreach($somearray as $value2)
 {
  if($value2['prop'][0]==$value1)
  {
    $final[$key][]='row'.$key.':'.$value1.'(uid:'.$value2['prop'][0].')'; // something like this
  }
 }
}
   //print_r($final);

foreach($final as $keyy => $farr)
{
 $myarr[$keyy]=implode(';',$farr);
}

//print_r($myarr);
   echo implode('<br/>',$myarr);