PHP - 根据原始数组中的爆炸名称创建新的数组值

时间:2015-11-13 17:55:59

标签: php arrays

我有这种格式的数组:

testing::UnitTest::GetInstance()

我需要找到具有$components = [ [ 'name' => 'ADIPIC ACID', 'cas' => '123', 'einecs' => '321' ], [ 'name' => 'ADIPIC ACID/DIMETHY- LAMINOHYDROXY- PROPYL DIETHYLENE- TRIAMINE COPOLYMER', 'cas' => '456', 'einecs' => '654' ] ] 字符的每个name,打破它并在 $ components 数组中创建一个新条目 cas einecs 为空字符串。

此名称的第一部分还会包含原始条目中的/cas值。

预期数组:

einecs

我该怎么做?

4 个答案:

答案 0 :(得分:1)

<?php

$components = [
    [
        'name'   => 'ADIPIC ACID',
        'cas'    => '123',
        'einecs' => '321'
    ],
    [
        'name'   => 'ADIPIC ACID/DIMETHY- LAMINOHYDROXY- PROPYL DIETHYLENE- TRIAMINE COPOLYMER',
        'cas'    => '456',
        'einecs' => '654'
    ]
];

$new = [];

foreach ($components as &$component) {
    if ($items = explode('/', $component['name'])) {
        $component['name'] = array_shift($items);
        $new = array_merge($new, $items);
    }
}

foreach ($new as $item) {
    $components[] = ['name' => $item, 'cas' => '', 'einecs' => ''];
}

var_dump($components);

答案 1 :(得分:1)

foreach($components as $component)
{
   if(strpos($component["name"],"/") !== false){
      $temp = explode("/",$component["name"]);
      $components[] = new array("name"=>$temp[1], "cas"=>"", "einecs"=>"");
   }
}

答案 2 :(得分:1)

相当粗略我承认并且它没有考虑值中的多个/个字符,但它确实返回了预期的结果。

        foreach( $components as $index=> $arr ){
            foreach( $arr as $key => $value ){
                if( $key=='name' && strstr( $value, '/' ) ){
                    list($pre,$post)=explode('/',$value);
                    $components[$index][$key]=$pre;
                    $components[]=array('name'=>$post,'cas'=>'','einecs'=>'');
                }
            }
        }

答案 3 :(得分:1)

我会尝试使用explode函数,在每个组件的名称上使用'/'字符。然后,我将创建一个包含被评估组件值的所有新组件的新数组。

$newComponents = array();
foreach($components as $component) {
  foreach(explode('/', $component['name']) as $newComponentName) {
    $newComponents[] = array('name'   =>$newComponentName, 
                             'cas'    => $component['cas'],
                             'einecs' => $component['einecs']);
  }
}