2016-11-10 4 views
-2

У меня проблема с массивами. У меня есть 3 массива. Я хочу сделать 1 строку, называемую историей, тогда она вставляет эту строку на основе shipment_id. если тот же shipment_id будет группировать один и тот же идентификатор доставки. См. Ожидаемый результат ниже.Как сохранить массив в массиве php

Array a ( 
[0] => Array ( 
    [order_id] => 231 
    [name] => "One Layer Lunch Box 
    [quantity] => 1 
    [username] => linkath 
    [shipment_id] => SI000116) 
[1] => Array ( 
    [order_id] => 231 
    [name] => "Test 03 
    [quantity] => 1 
    [username] => happymart 
    [shipment_id] => SI000117)) 
Array b ( 
[0] => Array ( 
    [shipment_id] => SI000116 
    [date] => 2016-11-09 09:40:26 
    [status] => Ready to ship 
    [description] => Your item(s) is being packed and ready for shipment at our vendor's warehouse.) 
[1] => Array ( 
    [shipment_id] => SI000116 
    [date] => 2016-11-09 10:16:04 
    [status] => Shipped 
    [description] => Your item(s) is being shipped with . For more details on your shipment, please go to Tracking, enter your tracking number)) 
Array c ( 
[0] => Array ( 
    [shipment_id] => SI000117 
    [date] => 2016-11-09 15:27:45 
    [status] => Ready to ship 
    [description] => Your item(s) is being packed and ready for shipment at our vendor's warehouse.)) 

Как и ожидалось массив

Array a ( 
[0] => Array ( 
    [order_id] => 231 
    [name] => "One Layer Lunch Box 
    [quantity] => 1 
    [username] => linkath 
    [shipment_id] => SI000116 
    [history] => Array b ( 
       [0] => Array ( 
        [shipment_id] => SI000116 
        [date] => 2016-11-09 09:40:26 
        [status] => Ready to ship 
        [description] => Your item(s) is being packed and ready for shipment at our vendor's warehouse.) 
       [1] => Array ( 
        [shipment_id] => SI000116 
        [date] => 2016-11-09 10:16:04 
        [status] => Shipped 
        [description] => Your item(s) is being shipped with . For more details on your shipment, please go to Tracking, enter your tracking number))) 
[1] => Array ( 
    [order_id] => 231 
    [name] => "Test 03 
    [quantity] => 1 
    [username] => happymart 
    [shipment_id] => SI000117 
    [history] => Array c ( 
       [0] => Array ( 
        [shipment_id] => SI000117 
        [date] => 2016-11-09 15:27:45 
        [status] => Ready to ship 
        [description] => Your item(s) is being packed and ready for shipment at our vendor's warehouse.)) 
      ) 
    ) 

Надеюсь понять, что я имею в виду. Заранее спасибо.

этот код, который им удалось. но не работает.

//tracker 
     $getshipment = $this->model_account_order->getshipmentByOrder($this->request->get['order_id']); 

     foreach ($getshipment as $shipment) { 
      $data['shipment'][] = array(
       'shipment_id' => $shipment['shipment_id'] 
      ); 
     } 
     $i=0; 
     foreach ($data['shipment'] as $key) { 
      $gethistorybysid[$i] = $this->model_account_order->getHistory($data['shipment'][$i]['shipment_id']); 
      $i++; 
     } 
     $u=0; 
     foreach ($getshipment as $final) { 
      $data['final'][] = array(
       'name'   => $shipment['name'], 
       'quantity'  => $shipment['quantity'], 
       'shipment_id' => $shipment['shipment_id'], 
       'history'  => array($gethistorybysid[$u]) 
      ); 
      $u++; 
     } 
     print_r($data['final']); 

этот код я не знаю, как сравнить тот же идентификатор доставки. У него есть какие-то способы?

+0

Невозможно помочь с выходом! Должен опубликовать ваш проверенный код ... –

+0

@ jitendrapurohit..im вставьте код, который им удалось. – ZackZeidy

+0

@ DavidJorHpan..pasted it .. – ZackZeidy

ответ

1

Вы можете использовать простые foreach() и array_column для достижения желаемого результата. Можете ли вы попробовать подход ниже, он должен работать.

//Loop the main Array A as follows 
foreach ($arrayA as $val) { 
    //Take the array B and C in a loop and check for shipment Id 
    foreach (array($arrayB, $arrayC) as $history) { 
    // Push the array in history key(of Array A) if the match is found. 
    if (in_array($val['shipment_id'], array_column($history, 'shipment_id')) { 
     foreach ($history as $value) { 
     $val['history'][] = $value; 
     } 
    } 
    } 
} 

Это всего лишь идея, я думаю, что это должно сработать, если нет, вы можете изменить в соответствии с вашими потребностями.

+1

Почему я не думал о 'array_column', я всегда, кажется, забыл, что эта функция существует. – Xorifelse

0

Что касается желаемого выхода:

# `array` is your first array where you want the shipments to be merged in. 
# `array_b` is the array containing the history. 

foreach($array as $contents){ 
    if(isset($contents['shipment_id'])){ 
     unset($match); 
     foreach($array_b as $key => $value){ 
      if(isset($value['shipment_id'])){ 
       if($value['shipment_id'] == $contents['shipment_id']){ 
        $match[] = $value['shipment_id']; 
       } 
      } 
     } 
     if(!empty($match)){ 
      $contents['shipment_id'] = $match; 
     } 
    } 
} 

Этот метод также сохранит значение shipment_id, когда никакой истории не найдено.

Однако, создание отдельной колонки, такой как jitendrapurohit's, является гораздо лучшим решением.