带有一个数组的PHP array_merge_recursive

时间:2016-12-15 15:27:59

标签: php arrays

我正在努力使用PHP中的数据结构。我正在尝试使用package sample; import javafx.application.Application; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.shape.Box; import javafx.scene.shape.DrawMode; import javafx.scene.shape.Rectangle; import javafx.scene.transform.Rotate; import javafx.stage.Stage; public class Example_Box extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box2 = new Box(); //Setting the properties of the Box box2.setWidth(100.0); box2.setHeight(100.0); box2.setDepth(100.0); //Setting the position of the box box2.setTranslateX(30); //450 box2.setTranslateY(90);//150 box2.setTranslateZ(300); //Setting the drawing mode of the box box2.setDrawMode(DrawMode.LINE); //Drawing an Image Image image = new Image("Lenna.png"); ImageView imageView = new ImageView(image); imageView.setTranslateX(200); imageView.setTranslateY(150); imageView.setTranslateZ(200); //imageView.getTransforms().add(new Rotate(30, 50, 30)); //Creating a Group object Group root = new Group(box2, imageView); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting camera PerspectiveCamera camera = new PerspectiveCamera(true); camera.setTranslateX(30); camera.setTranslateY(0); camera.setTranslateZ(-100); camera.setRotationAxis(new Point3D(1,0,0)); scene.setCamera(camera); //Setting title to the Stage stage.setTitle("Drawing a Box"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 通过类似的键压缩数组,然后获取所有值而不是覆盖它们。这就是我选择array_merge_recursive而不是array_merge_recursive的原因。

我的数组类似于:

array_merge

我希望Array ( [0] => Array ( [App] => APP1 [Type] => DB ) [1] => Array ( [App] => APP1 [Type] => WEBSITE ) [2] => Array ( [App] => APP2 [Type] => IOS ) ) 能够像键一样组合,然后将其他元素分组到数组中,但这不是我所看到的行为。

我希望得到如下数组:

array_merge_recursive

1 个答案:

答案 0 :(得分:2)

array_merge_recursive()没有按照您的想法行事。您正在寻找一个函数,该函数根据对您有帮助的特定规则重构数组,因此没有内置的php函数。即PHP如何知道您希望由APP而不是TYPE构建新数组。假设您的数组总是那么简单,那么您想要的最简单的函数版本如下所示:

function sortByApp($array){
    $result = array();
    foreach($array as $row){
        if(!isset( $result[ $row['APP'] ] ) {
            $result[ $row['APP'] ] = array(
                'APP' => $row['APP'],
                'TYPE' => array( $row['TYPE'] ) 
            );
        }else{
            $result[ $row['APP'] ]['TYPE'] = array_merge( $result[ $row['APP'] ]['TYPE'], array($row['TYPE']) );
        }
    }
    $result =  array_values($result); //All this does is remove the keys from the top array, it isn't really necessary but will make the output more closely match what you posted.

    return $result

}

注意,在此解决方案中,每个TYPEAPP键的值始终为数组。这使我以后更容易处理数据,因为您不必担心检查字符串与数组。