Viewed   87 times

I have the following array

Array
(
    [0] => Array
        (
            [id] => 96
            [shipping_no] => 212755-1
            [part_no] => reterty
            [description] => tyrfyt
            [packaging_type] => PC
        )

    [1] => Array
        (
            [id] => 96
            [shipping_no] => 212755-1
            [part_no] => dftgtryh
            [description] => dfhgfyh
            [packaging_type] => PC
        )

    [2] => Array
        (
            [id] => 97
            [shipping_no] => 212755-2
            [part_no] => ZeoDark
            [description] => s%c%s%c%s
            [packaging_type] => PC
        )

)

How can I group the array by id? Is there any native php functions are available to do this?

While this approach works, I want to do this using a foreach, since with the above I will get duplicate items, which I'm trying to avoid?

On the above example id have 2 items, so its need to be inside of the id

 Answers

4

There is no native one, just use a loop.

$result = array();
foreach ($data as $element) {
    $result[$element['id']][] = $element;
}
Monday, November 7, 2022
1

Actually, this can be done. Through a php extension.

File: config.m4

PHP_ARG_ENABLE(test, whether to enable test Extension support, [ --enable-test   Enable test ext support])

if test "$PHP_TEST" = "yes"; then
  AC_DEFINE(HAVE_TEST, 1, [Enable TEST Extension])
  PHP_NEW_EXTENSION(test, test.c, $ext_shared)
fi

File: php_test.h

#ifndef PHP_TEST_H
#define PHP_TEST_H 1

#define PHP_TEST_EXT_VERSION "1.0"
#define PHP_TEST_EXT_EXTNAME "test"

PHP_FUNCTION(getaddress4);
PHP_FUNCTION(getaddress);

extern zend_module_entry test_module_entry;
#define phpext_test_ptr &test_module_entry

#endif

File: test.c

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_test.h"

ZEND_BEGIN_ARG_INFO_EX(func_args, 1, 0, 0)
ZEND_END_ARG_INFO()

static function_entry test_functions[] = {
    PHP_FE(getaddress4, func_args)
    PHP_FE(getaddress, func_args)
    {NULL, NULL, NULL}
};

zend_module_entry test_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    PHP_TEST_EXT_EXTNAME,
    test_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
#if ZEND_MODULE_API_NO >= 20010901
    PHP_TEST_EXT_VERSION,
#endif
    STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_TEST
ZEND_GET_MODULE(test)
#endif

PHP_FUNCTION(getaddress4)
{
    zval *var1;
    zval *var2;
    zval *var3;
    zval *var4;
    char r[500];
    if( zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aaaa", &var1, &var2, &var3, &var4) == FAILURE ) {
      RETURN_NULL();
    }
    sprintf(r, "n%p - %p - %p - %pn%p - %p - %p - %p", var1, var2, var3, var4, Z_ARRVAL_P(var1), Z_ARRVAL_P(var2), Z_ARRVAL_P(var3), Z_ARRVAL_P(var4) );
    RETURN_STRING(r, 1);
}

PHP_FUNCTION(getaddress)
{
    zval *var;
    char r[100];
    if( zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &var) == FAILURE ) {
      RETURN_NULL();
    }
    sprintf(r, "%p", Z_ARRVAL_P(var));
    RETURN_STRING(r, 1);
}

Then all you have to do is phpize it, config it, and make it. Add a "extension=/path/to/so/file/modules/test.so" to your php.ini file. And finally, restart the web server, just in case.

<?php
  $x = array("123"=>"123");
  $w = $x;
  $y = $x;
  $z = &$x;
  var_dump(getaddress4($w,$x,$y,$z));
  var_dump(getaddress($w));
  var_dump(getaddress($x));
  var_dump(getaddress($y));
  var_dump(getaddress($z));
?>

Returns(at least for me, your memory addresses will probably be different)

string '
0x9efeb0 - 0x9effe0 - 0x9ef8c0 - 0x9efeb0
0x9efee0 - 0x9f0010 - 0x9ed790 - 0x9efee0' (length=84)

string '0x9efee0' (length=8)

string '0x9f0010' (length=8)

string '0x9ed790' (length=8)

string '0x9efee0' (length=8)

Thanks to Artefacto for pointing this out, but my original code was passing the arrays by value, so thereby was recreating arrays including the referenced-one, and giving you bad memory values. I have since changed the code to force all params to be passed by reference. This will allow references, arrays, and object, to be passed in unmolested by the php engine. $w/$z are the same thing, but $w/$x/$y are not. The old code, actually showed the reference breakage and the fact that the memory addresses would change or match when all variables were passed in vs multiple calls to the same function. This was because PHP would reuse the same memory when doing multiple calls. Comparing the results of the original function would be useless. The new code should fix this problem.

FYI - I'm using php 5.3.2.

Sunday, September 4, 2022
 
sk0x50
 
2
<?php

$elements = array(
    'tiger' => 'lion',
    'car' => 'bike',
    'lion' => 'zoo',
    'truck' => 'plane'
);

$groups = array();

foreach ($elements as $key => $val) {
    $appended = false;
    foreach ($groups as &$group) {
        if ($group[0] == $key) {
            array_unshift($group, $val);
            $appended = true;
            break;
        }
    }
    if (!$appended) {
        $groups[] = array($val, $key);
    }
}

var_dump($groups);

Gives:

array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(3) "zoo"
    [1]=>
    string(4) "lion"
    [2]=>
    string(5) "tiger"
  }
  [1]=>
  &array(2) {
    [0]=>
    string(4) "bike"
    [1]=>
    string(3) "car"
  }
  [2]=>
  array(2) {
    [0]=>
    string(5) "plane"
    [1]=>
    string(5) "truck"
  }
}
Wednesday, August 17, 2022
 
arnauld
 
5

You could try the following

Model.group("DATE_PART('hour', updated_at)").count

UPDATE:

How to find records

Model.where("DATE_PART('hour', updated_at) = ?", 5)
Wednesday, December 7, 2022
 
johnv
 
2

I'd like to have usefull data when programming in front-end. There are a few ways to handle the data you recieved. In my opinion it's the easiest way to manipulate the data you've got, so you are able to iterate through that month array, like following :

Your component

export class YourComponent {

    public months: any = [];
    public data: any = [];

    constructor() {
        this.data = [
            {
                'id': '75',
                'title': 'Oudergesprekken',
                'startDate': '18-01-2017',
            },
            {
                'id': '76',
                'title': 'Talentmiddag,te ontdekken.</p>',
                'startDate': '25-01-2017',
            },
            {
                'id': '77',
                'title': 'Studiedag team, alle kinderen vrij!',
                'startDate': '06-02-2017',
            },
            {
                'id': '79',
                'title': 'Letterfeest groep 3',
                'startDate': '14-02-2017',
            },
            {
                'id': '78',
                'title': 'Voorjaarsvakantie',
                'startDate': '24-02-2017',
            }
        ];
    }

    ngOnInit() {

        this.data.forEach( (event) => {
            let monthNumber = this.getMonthNumber(event);

            if (this.months[monthNumber] === null||undefined ) this.months[monthNumber].events = [];
            this.months[monthNumber].events.push(event);
        });

    }

    private getMonthNumber(event: any): number {
        return event.startDate.split('-')[1];
    }


    public getMonthName(monthNumber: any): number {
        let maanden = [ {"id": 1, "title": "Januari"}, {"id": 2, "title": "Februari"}, {"id": 3, "title": "Maart"}, {"id": 4, "title": "April"}, {"id": 5, "title": "Mei"}, {"id": 6, "title": "Juni"}, {"id": 7, "title": "Juli"}, ...... ];
        maanden.forEach((maand) => {
            if ( maand.id === monthNumber) return maand.title;
        });
    }
}

Your HTML

    <ion-item-group *ngFor="let month of months" >
        <ion-item-divider sticky *ngIf='month.events.length > 0'>{{getMonthName()}}</ion-item-divider>
        <ion-item *ngFor="let event of month.events | filter:{ maandNum:months.indexOf(month) }" >
          {{ item.title }}
        </ion-item>
    </ion-item-group>

I did not test this, so I'll keep an eye on this one. How this make some clear.

Sunday, October 2, 2022
 
ying
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :