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,
  ),
);

如何在 [prop] 的值等于 $somestring 中的相同值的条件下从 $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但它不处理重复值

4

2 回答 2

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>";
}


?>
于 2013-01-16T10:08:16.503 回答
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);
于 2013-01-16T09:00:43.953 回答