简体   繁体   中英

Foreach Loop PHP Once Stop

Currently I have a script that will collect data from an array and push it to an API, but for some reason i cant get it to add more then one at a time.

$data Array

array
(
    [0] => Array
        (
            [_id] => 0
            [_source] => App
            [_source_id] => 790006230e91dd6279a42a814bf5965a.jpg
            [_client_ids] => 2
            [_parent_ids] => 0
            [_image] => blank.jpg
            [_title] => test1
            [_body] => test1
        )

    [1] => Array
        (
            [_id] => 1
            [_source] => App
            [_source_id] => b3a5a6df0cf1dfc30882b20f8a493092.jpg
            [_client_ids] => 2
            [_parent_ids] => 0
            [_image] => blank.jpg
            [_title] => test2
            [_body] => test2
        )

)

PHP

public function save($data) {

        $submissionManager = new SubmissionManager($this->container);

        $returndata = array();

        foreach( $data as $entry )
        {

           $this->mustBeGranted('PERM_SUBMISSION_CREATE');

           $saved = array();

           $client_ids = explode(',', $entry['_client_ids']);
           $parent_ids = explode(',', $entry['_parent_ids']);
           $length = count($client_ids);

           for($i = 0; $i < $length; $i++){
                   $input = array_merge($entry, array(
                        'client_id' => isset($client_ids[$i]) ? $client_ids[$i] : 0,
                         'parent_id' => isset($parent_ids[$i]) ? $parent_ids[$i] : 0,
                        '_source_id' => $entry['_source_id']
                    ));
                    $saved[] = $submissionManager->createSubmission($input);
           }
           $returndata[ $entry['_id']] = $saved;
        }

    }

Basically it will only push the first array to the API and not the second one even though I've added a for-each.

Remove $saved=array() from foreach loop and put it before the loop. You are assigning empty array each time loop starts

I would say its likely that the value of $entry['_id'] is not changing so you are reassigning to the same array key.

Try instead using simply:

$returndata[] = $saved;

对不起,已解决的问题与我的createSubmission类有关……我的错

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM