Search code examples
phparraysvectormultidimensional-arrayscalar

Array of scalars and vectors at the same time in PHP


I have to create an array of the following "structure" in PHP:

user_id,array(item_id,flag,array(feedback_message_id))

Basically, for each user_id, there is an array of (item_id, flag, and an array of feedback_messages)..

Within a "classes" table, I have a field called "users" that holds data with separators. An example of data will be: |1-5-1-1~2~5|2-3-4-5~6~7|.......

I would need to put the data into an array as follows:

$myArray[0][0]="1";       // the first user's user_id = 0
$myArray[0][1][0]="5";    // the first user's first item's id = 5
$myArray[0][1][1]="1";    // the first user's first item's flag = 0
$myArray[0][1][2][0]="1"; // the first user's first item's first feedback message's id = 1
$myArray[0][1][2][1]="2"; // the first user's first item's second feedback message's id = 2
$myArray[0][1][2][2]="5"; // the first user's first item's third feedback message's id = 3

I don't know how to create such an array and how to retrieve data from it (syntax-wise)... I worked with single-dimensional arrays and multidimensional array, but this is an array partially bi-dimensional, partially tri and four-dimensional... is that even possible?


Solution

  • In your case array $a represent single user so get data like:

    $a=array( "user1", array( "item2", "DA", array ( "f1","f2","f3" ) ) );
    $user = $a[1][2][1]; //f2
    

    In common case it should be array of users:

    <?php
    $a = array( "user1", array( "item2", "DA", array ( "f1","f2","f3" ) ) ); 
    
    var_export($a[1][2][1]);
    
    
    $users = [
        ["user1", ["item2", "DA", [ "f1","f2","f3" ] ] ]
    ];
    
    echo PHP_EOL . PHP_EOL ."user" . PHP_EOL;
    $user = $users[0];
    
    var_export($user);
    
    echo PHP_EOL . PHP_EOL ."user item" . PHP_EOL . PHP_EOL;
    
    $user_item = $users[0][1][0];
    
    var_export($user_item);
    
    echo PHP_EOL . PHP_EOL ."user flag" . PHP_EOL . PHP_EOL;
    
    $user_flag = $users[0][1][1];
    
    var_export($user_flag);
    
    echo PHP_EOL . PHP_EOL ."user feedbacks" . PHP_EOL . PHP_EOL;
    
    $user_flag = $users[0][1][2];
    
    var_export($user_flag);
    
    
    echo PHP_EOL . PHP_EOL ."user second feedbacks" . PHP_EOL . PHP_EOL;
    
    $user_flag = $users[0][1][2][1];
    
    var_export($user_flag);
    

    share PHP code