使用特定键保存项目数组

时间:2017-10-06 09:05:53

标签: php arrays

如何使用数组键从数组中保存特定项目。

INPUT:

public class pdfreader {
    public static void main(String[] args) throws IOException, DocumentException, TransformerException {
        String SRC = "";
        String DEST = "";

        for (String s : args) {
            SRC = args[0];
            DEST = args[1];
        }
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new pdfreader().readText(SRC, DEST);
    }

    public void readText(String src, String dest) throws IOException, DocumentException, TransformerException {
         try {
                PdfReader pdfReader = new PdfReader(src);
                PdfReaderContentParser PdfParser = new PdfReaderContentParser(
                        pdfReader);
                PrintWriter out = new PrintWriter(new FileOutputStream(
                        dest));
                TextExtractionStrategy textStrategy;
                for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                    textStrategy = PdfParser.processContent(i,
                            new SimpleTextExtractionStrategy());
                    out.println(textStrategy.getResultantText());
                }
                out.flush();
                out.close();
                pdfReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

现在我只想保存密钥 2 43

预期输出:

$arr = [
    0 => 'item0',
    2 => 'item2',
    4 => 'item4',
    43 => 'item43'
];

当前代码:

$arr = [
   2 => 'item2',
   43 => 'item43'
];

现在可以使用了,但是如果我有更多的数组键可以保存呢。

3 个答案:

答案 0 :(得分:2)

你可以尝试这个。我们在这里使用array_intersect_keyarray_flip

  

array_intersect_key使用键计算数组的交集。

     

array_flip会将数组翻转到键和值上。

Try this code snippet here

<?php
ini_set('display_errors', 1);

$arr = [
    0 => 'item0',
    2 => 'item2',
    4 => 'item4',
    43 => 'item43'
];

$keys= [
    2,
    43
];
$result=array_intersect_key($arr, array_flip($keys));
print_r($result);
当前代码的

解决方案尝试here

您应该使用!=&&代替||

foreach ($arr as $key => $value) 
{
   if($key != 2 && $key != 43) 
   {
       unset($arr[$key]);
   }
}
print_r($arr);

答案 1 :(得分:1)

试试这段代码

        <?PHP
    $mykeys=array(2,5,9,7,3,4);

    foreach ($arr as $key => $value) {
       if(!(in_array($key,$mykeys) {
           unset($arr[$key]);
       }
    }?>

答案 2 :(得分:1)

你可以将你想要保存的密钥放在一个数组中,然后像这样迭代它:

$keys = array(); // put the keys here
foreach ( $arr as $key => $value) {
  $found = 0;
  foreach($keys as $filterKey) {
    if ($key == $filterKey) {
      $found = 1;
      break;
    }
    $found = 0;
  }
  if ($found == 0) {
    unset($arr[$key]);
  }
}