0

What I Need

  • i Need to create nesting array from existing array.
  • if in array both values type are same .
  • group according their type.
  • like array[1] type is same array[2] type so i need to group them in single nested array.

here is the array structure

                  $data=$event['data']['pricing_detail'];
                  [1] => Array
                  (
                  [type] => General Public Tickets Adult
                  [amount] => 50
                  [comment] => (Working Days)
                  )

                  [2] => Array
                  (
                  [type] => General Public Tickets Adult
                  [amount] => 80
                  [comment] => (Saturday/ Sunday/ Holiday)
                  )
  • i need output like

                  [1] => Array
                  (
                    [type] => General Public Tickets Adult
                    [metadata]=>array
                       (
                           [0] =>array
                            (
                               [amount] => 50
                               [comment] => (Working Days)
                            )
                            [1]=>array
                             (
                              [amount] => 80
                              [comment] => (Saturday/ Sunday/ Holiday)
                             )
                      )
                   )
    

code snippet

         $data=$event['data']['pricing_detail'];
         $metadata = array();
        foreach($data as $key => $value)
        {

                if($value[1]['type'] == $value[2]['type'])
            {

                $metadata[$key]['amount'] = $value['amount'];
                print_r($metadata);

            }
            else
            {
                  echo  "not matched";  

            }
        }
  • Problem im facing im not able to make logic so to get desired result.

2 Answers 2

1

Loop your array, storing the types and the array they belong to. Then loop the types and add te values.

//store types and the arrays the belong to    
foreach($data as $k=>$v){
    $type[$v['type']][]=$k;
    }

//loop types, creating result array
foreach($type as $k=>$v){
    $tmp=array(
        'type'=>$k,
        'metadata'=>array()
        );
      //loop all the arrays of this type
    foreach($v as $w){
                //store in TMP
    $t=array(
        'amount' => $vals[$w]['amount'],
        'comment' => $vals[$w]['comment']
                     );
                //sort TMP on EMPTY value
    usort($t,function ($a, $b) {
        if($a == '' && $b != '') return 1;
        if($b == '' && $a != '') return -1;
        if($b == 0){return 1;}
        return 0; 
        });
    //store 
    $tmp['metadata'][]=$t;
          }
    $result[]=$tmp;
    }

echo '<pre>'.print_r($result,true).'<pre>';

Example:

$data=array(
    1 => Array(
        'type' => 'General Public Tickets Adult',
      'amount' => 50,
      'comment' => '(Working Days)'),
      2 => Array    (
       'type' => 'General Public Tickets Adult',
       'amount' => 80,
       'comment' => '(Saturday/ Sunday/ Holiday)'),
    3 => Array  (
       'type' => 'Special Tickets Children',
       'amount' => 300,
       'comment' => '(Saturday/ Sunday/ Holiday)'),
    4 => Array  (
       'type' => 'Special Tickets Children',
       'amount' => 10000,
       'comment' => '(Monday afternoon)')
);

result:

Array
(
    [0] => Array(
            [type] => General Public Tickets Adult
            [metadata] => Array(
                    [0] => Array(
                            [amount] => 50
                            [comment] => (Working Days)
                        )
                    [1] => Array(
                            [amount] => 80
                            [comment] => (Saturday/ Sunday/ Holiday)
                        )
                )
        )

    [1] => Array(
            [type] => Special Tickets Children
            [metadata] => Array(
                    [0] => Array(
                            [amount] => 300
                            [comment] => (Saturday/ Sunday/ Holiday)
                        )
                    [1] => Array(
                            [amount] => 10000
                            [comment] => (Monday afternoon)
                        )
                )
        )
)

[edit] updated with usort for sorting empty 'comments';

[edit] added line to usort to prevent unwanted sorting when tickets = 0;

And a fiddle

Sign up to request clarification or add additional context in comments.

16 Comments

could you help me issue how to sort [comment] according data say structure if comment "string" should come at top else should be at lower index of array
I'm sorry, I don't understand exactly what you need
how t sort comment if [comment] is not empty there it should at top otherwise if [comment] is empty we should place empty comments lower order
You mean you'd like to switch them if the comment is empty? So the result array becomes [0] => Array( [comment] => 'dadada', [amount] =>10) or [0] => Array( [amount] =>99,[comment] => empty) ?
yes i just want to sort associative array according to empty/data
|
1

You have too create a new tickets array, with first dimention being the contents of type and second dimension being it's original id.

Something like this:

$grouped = array();
foreach($data as $key => $value) {
    $grouped[$value['type']][$key] = $value;
    unset($grouped[$value['type']][$key]["type"]);
}
print_r($grouped);

Adjust according to your array structure, I cant see the your actual structure of $data in your samples.


If you want to sort a multilevel array, you can use a variation of this function:

/**
 * sort an multidimensional array by any of it's fields and return sorted array
 * ex.: $sorted = multisort($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
 * IMPORTANT: This function uses mutlisort and will reindex numeric keys !
 * @param array $data       array to sort
 * @param string $field     name of field to sort by
 * @param int $direction    SORT_DESC or SORT_ASC constant
 * @return array
 */
 function multisort(){
     $args = func_get_args();
     $data = array_shift($args);

     foreach ($args as $n => $field) {
         if (is_string($field)) {
             $tmp = array();
             foreach ($data as $key => $row)
                 $tmp[$key] = $row[$field];
             $args[$n] = $tmp;
         }
     }

     $args[] = &$data;
     call_user_func_array('array_multisort', $args);
     return array_pop($args);        

}

Used like this:

foreach($grouped as $type => &$list)
    $list = multisort($list, 'comment', SORT_DESC);

1 Comment

could you issue how t sort comment if comment is there it should at top otherwise we should place empty comments lower order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.