PHP foreach with cURL和Multiple Array Merge to Multidimensional

时间:2017-04-04 19:18:48

标签: php arrays

我试图在foreach循环中发送一个cURL请求,然后返回多个数组并将它们放在一个数组中,以便在循环外部访问。这就是我所拥有的:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let myService: MyService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      imports: [ MaterializeModule, FormsModule, ReactiveFormsModule, HttpModule ],
      providers: [
        MyService,
        FormBuilder
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    slotsService = TestBed.get(MyService);
    fixture.detectChanges();
  });

  function updateForm(name, surname) {
    component.myForm.controls['name'].setValue(name);
    component.myForm.controls['surname'].setValue(name);
  }

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}

打印返回:

$array = array('1', '2', '3');

foreach ($array as $go){

//the cURl request occurs and returns the below variable. 

$json_result_dcam = json_decode($result_dcam);
$json_result_dcam_array = (array) $json_result_dcam;
echo "<pre>"; print_r($json_result_dcam_array);

}

我需要做的是将这些数组合并到一个我可以在循环外访问的多维数组。

3 个答案:

答案 0 :(得分:0)

最简单的形式,没有对响应进行任何进一步处理,就像:

$array = array('1', '2', '3');
$result = array();
$i = 0;

foreach ($array as $go){

//the cURl request occurs and returns the below variable. 

$json_result_dcam = json_decode($result_dcam);
$json_result_dcam_array = (array) $json_result_dcam;
   foreach ($json_result_dcam_array as $header){
       $result[$i] = $header;
       $i++;
   }


}
echo "<pre>"; print_r($result);

答案 1 :(得分:0)

您可以简单地将所有结果添加到一个数组中,然后您可以稍后迭代,即:

$json_result_dcam = [];
$array = array('1', '2', '3');

foreach ($array as $go){
    //the cURl request occurs and returns the below variable. 

    $json_result_dcam[] = json_decode($result_dcam, true);
}

var_dump($json_result_dcam);

答案 2 :(得分:0)

你可以在数组中使用数组

选项1 将它们声明为数组数组

$myAoA = array( array(), array(), array() );

选项2

使用array_pop方法将项​​添加到数组的末尾

$myAoA = [];
array_push($myAoA, $myArr1);
array_push($myAoA, $myArr2);
array_push($myAoA, $myArr3);

将这些按顺序排列

[ $myArr1, $myArr2, $myArr3 ]

选项3

使用array_unshift方法将项​​目添加到数组的开头

$myAoA = [];
array_unshift($myAoA, $myArr1);
array_unshift($myAoA, $myArr2);
array_unshift($myAoA, $myArr3);

将这些按顺序排列

[ $myArr3, $myArr2, $myArr1 ]