Friday 31 August 2018

Create a multidimensional array from four arrays based on the parent ID

From these four arrays:

$root = (FORD, FIAT, GM, KIA, FERRARI);
$parentIsFiat = (Panda, Punto, Tipo);
$parentIsPanda = (1, 13, 16, 20);
$parentIs13 = (Red, Blue, White);

How can I create a multidimensional array to give me this:
FORD
FIAT
--Panda
----1
----13
------Red
------Blue
------White
----16
----20
--Punto
--Tipo
GM
KIA
FERRARI

Background: The current menu on my site has every link on the site in the HTML. I want to only have the HTML for menu items that are actually visible. At the moment I get each item in the path (FIAT > Panda > 13) and it's siblings with code similar to this:
$categoryPath = \XLite\Core\Database::getRepo('\XLite\Model\Category')->getCategoryPath($this->getCategoryId());
foreach ($categoryPath as $category) {
    $currentCatID = $category->getID();
    $currentCatSiblings = $category->getSiblings(true);
    foreach ($currentCatSiblings as $sibling) {
        $menuItems[$currentCatID][] = $sibling->getName(); // the four arrays above
    }
}

Each of the arrays has the parent ID as the key so I can 'attach' it in the correct place but I don't know how to build the array from my four existing arrays.

You could introduce a temporary $parent variable that will reference the place in the tree where the siblings must be inserted, and move that $parent reference further down the tree for the next "generation" of siblings:
$tree = [];
$parent = &$tree; // Use `= &` to reference the same location
foreach ($categoryPath as $category) {
    $currentCatID = $category->getID();
    $currentCatSiblings = $category->getSiblings(true);
    foreach ($currentCatSiblings as $sibling) {
        $parent[] = [ "name" => $sibling->getName() ];
        if ($sibling->getID() === $currentCatID) $index = count($parent) - 1;
    }
    $parent[$index]["children"] = [];
    $parent = &$parent[$index]["children"]; // Use `= &` to reference the deeper location
}

At the end $tree will contain the nested array. It will have "children" keys to store the nested structure, like this:
[
  [ "name" => "Ford" ],
  [
    "name" => "Fiat",
    "children" => [
      [
        "name" => "Panda",
        "children" => [
          [ "name" => "1" ],
          [
            "name" => "13",
            "children" => [
              [ "name" => "Red" ],
              [
                "name" => "Blue",
                "children" => [],
              ],
              [ "name" => "White" ],
            ],
          ],
          [ "name" => "16" ],
          [ "name" => "20" ],
        ],
      ],
      [ "name" => "Punto" ],
      [ "name" => "Tipo"  ],
    ],
  ],
  [ "name" => "GM" ],
  [ "name" => "Kia" ],
  [ "name" => "Ferrari" ],
]

Or, if you prefer to have the names used as keys in an associative array, then:
$tree = [];
$parent = &$tree; // Use `= &` to reference the same location
foreach ($categoryPath as $category) {
    $currentCatID = $category->getID();
    $currentCatSiblings = $category->getSiblings(true);
    foreach ($currentCatSiblings as $sibling) {
        $parent[$sibling->getName()] = [];
    }
    $parent = &$parent[$category->getName()]; // Use `= &` to reference the deeper location
}

Result:
[
  "Ford" => [],
  "Fiat" => [
    "Panda" => [
      "1" => [],
      "13" => [
        "Red" => [],
        "Blue" => [],
        "White" => []
      ],
      "16" => [],
      "20" => []
    ],
    "Punto" => [],
    "Tipo" => []
  ],
  "GM" => [],
  "Kia" => [],
  "Ferrari" => []
]

PHP Create a multidimensional array from the keys

Is there a way to create dynamicaly multidimensional array? I have stored in database "path" for each field=>value like that:

field_name : [slideshow][slide][0][title]
field_value : my title

field_name : [slideshow][slide][0][desc]
field_value : my desc

field_name : [slideshow][slide][1][title]
field value : my other title

field_name : [slideshow][slide][1][desc]
field value : my other desc

field_name : [slideshow][settings][duration]
field value : 300

and now I'm trying to figure out how to make it an array again. Obviously there can be lots of fields and complexity so I wanted to avoid some recursions if possible, cause I'm not sure how it will impact performance.
I was playing around with variable variables and trying something like:
$array_name = 'arr';
${$array_name}[slideshow][slide][1][title] = $field->field_value;
print_r($arr);

but this works only if its literally that, and nothing like this works:
${$array_name}.$field->field_name = $field->field_value;

I basically need to store every field as individual row (e.g. for searches in those fields), values can be diffrent types (even serialized arrays), and contain html.
Any advice appreciate.

The basic idea is to split up your field_name string and loop over the parts backward to build up the array. Some recursion is used to merge the arrays, though any performance impact should be negligible.

Example:

// Set up sample data.
$field = new stdClass();
$field->field_name = '[slideshow][slide][0][title]';
$field->field_value = 'my title';
$fields[] = $field;

$field = new stdClass();
$field->field_name = '[slideshow][slide][0][desc]';
$field->field_value = 'my desc';
$fields[] = $field;

$field = new stdClass();
$field->field_name = '[slideshow][slide][1][title]';
$field->field_value = 'my other title';
$fields[] = $field;

$field = new stdClass();
$field->field_name = '[slideshow][slide][1][desc]';
$field->field_value = 'my other desc';
$fields[] = $field;

$field = new stdClass();
$field->field_name = '[slideshow][settings][duration]';
$field->field_value = '300';
$fields[] = $field;
// End sample data.

// array_merge_recursive() doesn't do what we want with numeric keys, so use this
function merge($base, $array) {
    foreach ($array as $key => $value) {
        if (isset($base[$key]) && is_array($base[$key]) && is_array($value)) {
            $base[$key] = merge($base[$key], $value);
        } else {
            $base[$key] = $value;
        }
    }
    return $base;
}

$result = [];
foreach ($fields as $field) {
    $parts  = array_reverse(explode('][', trim($field->field_name, '[]')));
    $value = $field->field_value;
    foreach ($parts as $part) {
        $value = [$part => $value];
    }
    $result = merge($result, $value);
}
print_r($result);


Output:

Array
(
    [slideshow] => Array
        (
            [slide] => Array
                (
                    [0] => Array
                        (
                            [title] => my title
                            [desc] => my desc
                        )

                    [1] => Array
                        (
                            [title] => my other title
                            [desc] => my other desc
                        )

                )

            [settings] => Array
                (
                    [duration] => 300
                )

        )

)

Create a multidimensional array from a database table

I have a mysql table which contains is:

folder_id (int(11), auto increment)
folder_name (varchar)
folder_class(varchar)
folder_link (varchar)

What I want to do is somehow loop through the table and store each row like this:
$packs = array( array(  'Name'  => 'DarkUIPack',
                    'Class' => 'ui',
                    'Link'  => 'http://graphicriver.net/item/dark-minimalist-ui-pack/662762'
                ),
            array(  'Name'  => 'MinimalistIcons',
                    'Class' => 'min',
                    'Link'  => 'http://graphicriver.net/item/small-minimalist-icons-pack/670469'
                ),
            array(  'Name'  => 'BlueMediaIcons',
                    'Class' => 'blue',
                    'Link'  => 'http://graphicriver.net/item/blue-media-icons-set/705319'
                ),
            array(  'Name'  => 'MediaIcons',
                    'Class' => 'med',
                    'Link'  => 'http://graphicriver.net/item/media-icons-set/679835'
                ),
            array(  'Name'  => 'ToTheTopButtons',
                    'Class' => 'top',
                    'Link'  => 'http://graphicriver.net/item/to-the-top-buttons/673221'
                ),
            array(  'Name'  => 'Sunglasses',
                    'Class' => 'sun',
                    'Link'  => ''
                ),
            array(  'Name'  => 'RealEstate',
                    'Class' => 'est',
                    'Link'  => 'http://graphicriver.net/item/simple-real-estate-logo/724697'
                ),
            array(  'Name'  => 'PhotoStudio',
                    'Class' => 'std',
                    'Link'  => 'http://graphicriver.net/item/photo-studio-logo/724694'
                ),
            array(  'Name'  => 'PayDayCity',
                    'Class' => 'std',
                    'Link'  => ''
                ),
            array(  'Name'  => 'MoleculeCorp',
                    'Class' => 'mol',
                    'Link'  => 'http://graphicriver.net/item/molecule-corp-logo/719307'
                ),
            array(  'Name'  => 'ClubbGX',
                    'Class' => 'gx',
                    'Link'  => ''
                ),
            array(  'Name'  => 'AerialVision',
                    'Class' => 'aer',
                    'Link'  => ''
                ),
            array(  'Name'  => 'ServiceCompany',
                    'Class' => 'ser',
                    'Link'  => 'http://graphicriver.net/item/service-company-logo/727091'
                ),
            array(  'Name'  => 'ElectroTech',
                    'Class' => 'ele',
                    'Link'  => 'http://graphicriver.net/item/electro-tech-logo/720904'
                ),
            array(  'Name'  => 'CreativeStudio',
                    'Class' => 'cre',
                    'Link'  => 'http://graphicriver.net/item/creative-studio-logo/719494'
                ),
            array(  'Name'  => 'NanoCorp',
                    'Class' => 'nan',
                    'Link'  => 'http://graphicriver.net/item/nano-corp-logo/719098'
                ),
            array(  'Name'  => 'RehabPlace',
                    'Class' => 'reh',
                    'Link'  => ''
                ),
            array(  'Name'  => 'MyLocalMix',
                    'Class' => 'mix',
                    'Link'  => ''
                ),
            array(  'Name'  => 'SevenBySeven',
                    'Class' => 'sev',
                    'Link'  => ''
                ),
            array(  'Name'  => 'ComingSoon',
                    'Class' => 'com',
                    'Link'  => ''
                ),
            array(  'Name'  => 'AlienIcons',
                    'Class' => 'aln',
                    'Link'  => 'http://graphicriver.net/item/alien-icons-set/698515'
                ),
            array(  'Name'  => 'PreloaderPortfolio',
                    'Class' => 'pre',
                    'Link'  => ''
                ),
            array(  'Name'  => 'BioTech',
                    'Class' => 'bio',
                    'Link'  => ''
                ),
            array(  'Name'  => 'ConstructionCompany',
                    'Class' => 'con',
                    'Link'  => ''
                ),
            array(  'Name'  => 'EagleMedia',
                    'Class' => 'egl',
                    'Link'  => ''
                ),
            array(  'Name'  => 'ElectronicWays',
                    'Class' => 'elw',
                    'Link'  => ''
                ),
            array(  'Name'  => 'EnvironmentalCompany',
                    'Class' => 'env',
                    'Link'  => ''
                ),
            array(  'Name'  => 'SecureData',
                    'Class' => 'sec',
                    'Link'  => 'http://graphicriver.net/item/secure-data-company-logo/907334'
                ),
            array(  'Name'  => 'ConstructSimple',
                    'Class' => 'cns',
                    'Link'  => 'http://graphicriver.net/item/simple-construction-company-logo/907538'
                ),
            array(  'Name'  => 'ConstructRoof',
                    'Class' => 'cnr',
                    'Link'  => 'http://graphicriver.net/item/construction-company-logo/907549'
                )
        );

where 'Name' corresponds to folder_name, 'Class' to folder_class and 'Link' to folder_link.
I'm using this within a class and the class looks like this till now:
class folder
{
private $connect;

public function __construct() {

    $this->connect = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    if (mysqli_connect_errno()) {
        $error = true;
        $message['error'] = true;
        $message['message'] = mysqli_connect_error();
        return json_encode($message);
    }
        else {
            return true;
        }

}

    public function crtFolder($fldName,$fldClass,$fldLink,$fldPath) {

    $fldName = preg_replace('/\s+/', '', $fldName);

    $fldPN = $fldPath."\\".$fldName;

    $modArray = array(array('1'));

    if ((!is_dir($fldPN))) {
        if(mkdir($fldPN,0777,true)) {

            $sql = "INSERT INTO folders (folder_name,folder_class,folder_link) VALUES (?, ?, ?)";

            if($stmt = $this->connect->prepare($sql)) {
                $stmt->bind_param("sss", $fldName, $fldClass, $fldLink);
                $stmt->execute();
                $stmt->close();
                $error = false;
                $message['error'] = false;
                $message['message'] = "Folder Created | Data Successfuly Inserted";
                return json_encode($message);
            }
                else {
                    $error = true;
                    $message['error'] = true;
                    $message['message'] = "Folder Created | Data Failed To Insert";
                    return json_encode($message);
                }
        }
            else {
                $error = true;
                $message['error'] = true;
                $message['message'] = "Folder Failed To Create";
                return json_encode($message);
            }
    }
        else {
            $error = true;
            $message['error'] = true;
            $message['message'] = "Folder Already Exists";
            return json_encode($message);
        }
}

public function __destruct() {

    $closeConnection = $this->connect->close();

    if($closeConnection) {
        return true;
    }
}

}
I'm showing the class because I want to keep the same method for the creating the array as the other methods are created. Because I found something on Google, but it was making an array from multiple tables. I only have one table.

Write below given function in to your class. Hope this will help things.
public function getTableData(){

 $sql = "SELECT * FROM folders";
 if($stmt = $this->connect->prepare($sql)) {

     $stmt->execute();
     $stmt->close();
     $arrFinalArray = array();
     while ($arrFolder = $stmt->fetch()){

        $arrFinalArray[] = array(
                    'Name'  => $arrFolder['folder_name'],
                    'Class' => $arrFolder['folder_class'],
                    'Link'  => $arrFolder['folder_link']
        );

     }
  }
}

How do you create a multidimensional array from SQL data stored hierarchically using the adjacency list method?

Hierarchical Data from SQL

Adjacency List Model

In my model I have a series of objects, each stored with their parent id. I am using the Adjacency list model as my hierarchy method.
All examples of Adjacency list simply output there and then. None try to create a multi dimensional array from the result set.
---------------
| id | parent |
---------------
| 1  | NULL   |
| 2  | 1      |
| 3  | 1      |
| 4  | 2      |
| 5  | 2      |
| 6  | 5      |
---------------

Object

I created an array variable in my class called 'children' and want to add a child object each time I find a child from the db query.
Creating an array within each object and storing the subsequent objects in there feels wrong. Can't I create the array of objects separately? Doing it this way may make it hard to traverse the array when I get it into the view.
I feel like I am I approaching this problem the wrong way?
Is there a smarter way to use PHP arrays than this?

The array of children doesn't have to be part of a class; you can always just make an ad-hoc tree where one node is a hash containing an object and its children. I don't know PHP, but it would look something like:
{
    object => $row1,
    children => [
        {
            object => $row2,
            children => [ ... ],
        }, {
            object => $row3,
            children => [],
        }
    ]
}

PHP - Create a multidimensional array from a one-dimensional array

Ok, so i have this string array that looks something like this:

myArray[0] = "a0,b0,c0,d0"
myArray[1] = "a1,b1,c1,d1"
myArray[2] = "a2,b2,c2,d2"
myArray[3] = "a3,b3,c3,d3"
etc...

I want to create a multidimentional array that uses the first part of each element as "key". In short:
myMultiArray:
x/y|  0   |  1   |  2   |  3   |
------------------------
 0 | "a0" | "a1" | "a2" | "a3" |
 1 | "b0" | "b1" | "b2" | "b3" |
 2 | "c0" | "c1" | "c2" | "c3" |
 3 | "d0" | "d1" | "d2" | "d3" |

this is what I've got:
 private String[,] resultsParser(String[] inputArray)
    {
        String[] splittedString = null;
        String[,] outputString = null;
        for (int i = 0; i < inputArray.Length; i++ )
        {
            splitString = inputArray[i].Split(',');
            for (int j = 0; j < outputArray.GetLength(0); j++)
            {
                if (splitString[0] == outputArray[j, 0])
                {
                    for (int k = 1; k < splitString.Length; k++)
                    {
                        outputArray[j, k] = splitString[k];
                    }
                }
            }
            for (int k = 0; k < splitString.Length; k++)
            {
                outputArray[outputArray.GetLength(0), k] = splitString[k];
            }
        }
        return outputArray;
    }

  • Problem1: it doesn't work
  • Problem2: the code is fugly
Is there some easy way of doing this?

It seems to me you need to separate this into two stages:
  • Determining the size
  • Splitting each row and copying the results
Each of these is reasonably simple, but you'll find the code much simpler if you separate them. Something like:
public static string[,] SplitResults(string[] input)
{
    int columns = input[0].Split(',').Length;
    string[,] output = new string[input.Length, columns];

    for (int row = 0; row < input.Length; row++)
    {
        string[] split = input[row].Split(',');
        for (int column = 0; column < columns; column++)
        {
            output[row, column] = split[column];
        }
    }
    return output;
}

However, you should add validation:
  • input should not be null
  • input should not be empty
  • Every row should be the same size
Note that the code above splits the first row twice (once to find the size, and once to populate the data). While you could fix that to be more efficient, it would make the code more ugly - I wouldn't do it unless you really found it to be a bottleneck.

Sort the multidimensional array from top to bottom in PHP

I have checked on here and cant find a similar result so if this has been asked I do apologies.

Anyway, I am generating an multi array which has been generated by a nice little class.
Anyway the array comes like this when output:
array(2047) {
    [0]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "26"
    }
    [1]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "42"
    }
    [2]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "16"
    }
    // and so on
}

My question is... Is there an easy php function or a neat way on sorting the array into high to low using the points value?
I have had a look at a few php functions but they are just for standard arrays with a single value.
Thanks for any help given :)
UPDATE
I have tried this and it does not sort by points.
Here is the class I am doing it with:
//create sort value
private function sorting_table($a, $b){
    return $a['points'] - $b['points'];
}

//sort all users into a table and order the highest to the lowest
public function output_prediction_table($pdo, $year){

    //get all uers and put in an array with games played and points.
    $getallusers = $pdo->prepare("SELECT userid FROM userpredictions WHERE year=:year");
    $getallusers->execute(array(':year' => $year));

    //create the multidimentional array
    $multidimentional_array = array();

    while($fetchallusers = $getallusers->fetch()){

        $multidimentional_array[] = array(
            'name' => $this->get_username($pdo, $fetchallusers['userid']),
            'games' => $this->get_games_played($pdo, $year),
            'points' => $this->make_points($pdo, $year, $fetchallusers['userid']),
            'userid' => $fetchallusers['userid']
        );

    }

    usort($multidimentional_array, array($this, 'sorting_table'));

    $output = '<table class="table-striped">';
    $output .= '<tr class="t-h"><td class="t-c">Position</td><td>Username</td><td>Games Played</td><td>Points</td></tr>';
    $tablenumber = 1;

    foreach($multidimentional_array as $newarray){

        $output .= '<tr><td class="t-c">'.$tablenumber.'</td><td><a href="/user/'.$this->sluggify($newarray["name"]).'/'.$newarray["userid"].'/" title="View '.ucwords($newarray["name"]).' Profile">'.ucwords($newarray["name"]).'</a></td><td>'.$newarray["games"].'</td><td>'.$newarray["points"].'</td></tr>';
        $tablenumber++;

    }

    $output .= '</table>';

    return $output;

}

I am not getting any errors, its just not sorting with the highest points first to the lowest points last.

Try usort
You can do something like this:
usort($array, 'sortByPoints');

function sortByOrder($a, $b) {
    return $a['points'] - $b['points'];
}

Yo can find more examples here: Sort Multi-dimensional Array by Value

How do I create an associative array from a foreach loop?



$array = ["farm"=>
              [
                "horse"=>
                 [
                  "rabbit"=>
                     [
                      "fred1"=> "fred1",
                      "fred2"=> "fred2",
                      "fred3"=> "fred3",
                      "fred4"=> "fred4"
                    ],
                 "raccoon"=>
                    ["frida"=> "frida"]
                  ]
              ]
    ];

I want to create an array from my for each loop:
$keySearch = "o";

    function createList($array, $keySearch, $path) {
        foreach ($array as $key => $item) {
            $basePath = $path === null ? $key : $path. "/" . $key;
               if(is_array($item)){
                  if (stripos($key, $keySearch) !== false){
                     $a['key'] = $key ;
                     $b['basePath'] = $basePath;
                     $result[] = array_merge_recursive ($a, $b);
                  }
                 createList($item, $keySearch, $basePath);
                }
        }
    print_r($result);
    }
    createList($array, $keySearch, '');

My result is:
Array
(
    [0] => Array
        (
            [key] => horse
            [basePath] => farm/horse
        )

)
Array
(
    [0] => Array
        (
            [key] => raccoon
            [basePath] => farm/horse/raccoon
        )

)

What I actually expect is:
 Array
    (
        [0] => Array
            (
                [key] => horse
                [basePath] => farm/horse
            )
        [1] => Array
            (
                [key] => raccoon
                [basePath] => farm/horse/raccoon
            )

    )


i improved your code:
 function createList($array, $keySearch, $path=null) {
    $result = [];
    foreach ($array as $key => $item) {
        $basePath = $path === null ? $key : $path. "/" . $key;
           if(is_array($item)){
              if (stripos($key, $keySearch) !== false) {
                 $result[] = ['key' => $key, 'basePath' => $basePath];
              }
             $result = array_merge($result, createList($item, $keySearch, $basePath));
            }
    }
return $result;
}

$keySearch = 'o';
$res = createList($array, $keySearch);
print_r($res);

UPD: if you find all keys, not only those which points array, change code so:
function createList($array, $keySearch, $path=null) {
              $result = [];
    foreach ($array as $key => $item) {
        $basePath = $path === null ? $key : $path. "/" . $key;
        if (stripos($key, $keySearch) !== false)
             $result[] = ['key' => $key, 'basePath' => $basePath];
        if(is_array($item))
             $result = array_merge($result, createList($item, $keySearch, $basePath));
    }
return $result;
}

$keySearch = 'fr';
$res = createList($array, $keySearch);
print_r($res);

PHP putting four dates in an array from a while loop

Using the below while loop, I get four dates in the echo, which is what I need.

$data = [];

$start = Carbon::createFromDate('2016', '04', '01');
$end = Carbon::createFromDate('2017', '04', '01');

while($start < $end)
{
    $data[] = $start;

    echo $start;

    $start->addMonths('3');
}

Output:
2016-04-01
2016-07-01
2016-10-01
2017-01-01

But when I dump the $data[] array, I just get four collections, each with the same date:
2017-04-01

What am I doing wrong? I just want to put the above four dates in an array.

You're assigning an object instance ($start) to each array entry (and objects are "by reference"), and modifying that object instance, so the same object instance is being changed wherever.... assign a "clone" into your array
while($start < $end)
{
    $data[] = clone $start;
    echo $start;
    $start->addMonths('3');
}

Getting a random array of a while loop in PHP

I have a page set up for testimonials for a company website. Just the standard message first name, last name, message, blah blah..anyways I can pull the message up and have a single entry show up however, I would like it to randomly generate a 'testimonial' I know there is random_array functions already included in PHP but how would I go about it in a while loop? Thats the only way really I have learned to pull information from a MySQL database. So if there is a simpler way I am all ears.

<?php
    mysql_select_db("test", $link);
    $sql= "SELECT * FROM testimonials LIMIT 1";

    $result = mysql_query($sql);
    while($row = mysql_fetch_assoc($result)){
        // var_dump($row['message']); die;
?>
    <p>
<?php
    echo $row['message']; ?>"<br/>
    <div id="quote"><?php echo $row['first_name']. " " .$row['last_name'];?></div><div id="location"><?php echo $row['city']. " , " .$row['state'];?></div><br/>

    <div class="readmore">
        <a href="greenInformation.php">Click Here to view more</a>
    </div></p>

<?php } ?>


Like this?
$sql="SELECT * FROM `testimonials` ORDER BY RAND() LIMIT 1";

Another, and better method, is if you have a ID column, then you could generate a random number and get a row based on that.
$sql="SELECT * FROM `testimonials` WHERE `id`=".mt_rand(1,500);

To create a multidimensional array from a while loop in PHP

I am losing my mind with this. I have a while loop that I am making into an array. I then want to pass that array to another function but it keeps failing. I know that it is failing for some formatting error, but I can't for the life of me figure out how to get it to format properly.

Here is the format I NEED:
array(
    'id'       => 'some-id',
    'field1'   => 'somefield',
    'field2'   => 'someotherfield',
    'title'    => 'title',
    'subarray' => array(
        'sub1'  => 'subonevalue',
        'sub2' => 'sub2value'
    )
),
array(
     'id'       => 'some-other-id',
    'field1'   => 'some-other-field',
    'field2'   => 'some-other-otherfield',
    'title'    => 'other title',
    'subarray' => array(
        'sub1'  => 'othersubonevalue',
        'sub2' => 'othersub2value'
    )
),

I am outputting a while loop, and have tried the following:
global $wp_query;
$the_query = new WP_Query( 'post_type=mycustomposttype' );
$pointer_query = array();

while ( $the_query->have_posts() ) : $the_query->the_post(); 

$pointer_query[] = array(
    'id'       => get_post_meta( $post->ID, 'keyid', true ),
    'field1'   => get_post_meta( $post->ID, 'field1key', true ),
    'field2'   => get_post_meta( $post->ID, 'field2key', true ),
    'title'    => get_the_title($post->ID),
    'subarray' => array(
        'sub1'  => get_post_meta( $post->ID, 'sub1key', true ),
        'sub2' => get_post_meta( $post->ID, 'sub1key', true )
    )
);
endwhile;
endif;

Unfortunately, that gives me back something like this:
Array
(
[0] => Array
    (
        [id] => first-id
        [field1] => first-field1
        [field2] => first-field2
        [title] => first title
        [subarray] => Array
            (
                [sub1] => first-sub1
                [sub2] => first-sub2
            )

    )

[1] => Array
    (
        [id] => second-id
        [field1] => second-field1
        [field2] => second-field2
        [title] => second title
        [subarray] => Array
            (
                [sub1] => second-sub1
                [sub2] => second-sub2
            )

    )

)

Which does NOT match the format I need, and is causing errors. I feel like there is some simple PHP transformation I am missing here, but after hours of searching I have turned up blank, and now I am depressed and frustrated. Can anyone help me please?
UPDATE (because the comments below are crappy for formatting code):
I just want to pass the array represented in the while loop ($pointer_query) to something like the following, here it is in full (although I have ALSO tried to put it in its own function and call it from the other function, hence the notation below in the comments.
function MyPointers()
{
    global $wp_query;
$the_query = new WP_Query( 'post_type=mycustomposttype' );
$pointer_query = array();

while ( $the_query->have_posts() ) : $the_query->the_post(); 

$pointer_query[] = array(
    'id'       => get_post_meta( $post->ID, 'keyid', true ),
    'field1'   => get_post_meta( $post->ID, 'field1key', true ),
    'field2'   => get_post_meta( $post->ID, 'field2key', true ),
    'title'    => get_the_title($post->ID),
    'subarray' => array(
        'sub1'  => get_post_meta( $post->ID, 'sub1key', true ),
        'sub2' => get_post_meta( $post->ID, 'sub1key', true )
    )
);
endwhile;
endif;  

$pointers = array($pointer_query);
new SS_Pointer( $pointers );
}

Which then calls a separate class SS_Pointer. But the problem is in the $pointers array.

By the time you declare $pointers as an array, $pointer_query already is an array. If you were to var_dump after your $pointers declaration you would see:
Array
(
    Array
    (
    [0] => Array
        (
            [id] => first-id
            [field1] => first-field1
            [field2] => first-field2
            [title] => first title
            [subarray] => Array
                (
                    [sub1] => first-sub1
                    [sub2] => first-sub2
                )

        )

    [1] => Array
        (
            [id] => second-id
            [field1] => second-field1
            [field2] => second-field2
            [title] => second title
            [subarray] => Array
                (
                    [sub1] => second-sub1
                    [sub2] => second-sub2
                )

        )

    )
)

That is, $pointers will be an array which contains one entry: an array that would have a structure exactly as you describe in the array declaration at the beginning of your question. So change:
$pointers = array($pointer_query);
new SS_Pointer( $pointers );

to:
new SS_Pointer( $pointer_query );

And then the SS_Pointer class should then receive an array with a structure it expects.

The php code does not convert to html

I have a php code

<select style="width: 200px;" name="location" id="myselect" onchange="window.location='enable1.php?id='+this.value+'&pos='+this.selectedIndex;">
  <option value="All">All</option>
 <?php

  $sql="select * from location";
  var_dump($sql);
  $query=mysqli_query($conn,$sql);
  echo "1";
  while($row=mysql_fetch_array($query))
  {
      echo "<option value='$row[loc]'>'$row[loc]'</option>";
  }
    ?>

</select>

In this code i echo"options" but instead of that when I view source code I see php part written not options..

You used mysql_fetch_array() instead of mysqli_fetch_array()... Try this...
<select style="width: 200px;" name="location" id="myselect" onchange="window.location='enable1.php?id='+this.value+'&pos='+this.selectedIndex;">
<option value="All">All</option>
 <?php

  $sql="select * from location";
  var_dump($sql);
  $query=mysqli_query($conn,$sql);
  echo "1";
  while($row=mysqli_fetch_array($query))
  {
      echo "<option value='$row[loc]'>'$row[loc]'</option>";
  }
    ?>

</select>

The PHP code does not work, does not connect to the mysql database

I'm trying to get simple form data added to mysql database via php.

This is my php code..
$dbc = mysqli_connect('localhost','root','sahunihal123321','aliendatabase')
or die('Error connecting to MySQL server.');

$query="INSERT INTO aliens_abduction (first_name,last_name,when_it_happened,how_long, " .
"how_many,alien_description,what_they_did,fang_spotted,other,email)" .
"VALUES ('$first_name','$last_name','$when_it_happened','$how_long','$how_many', " .
"'$alien_description','$what_they_did','$fang_spotted','$other','$email')";

$result=mysqli_query($dbc,$query)
or die('Error querying database.');
mysqli_close($dbc);

  echo 'Thanks for submitting the form.<br />';
  echo 'You were abducted ' . $when_it_happened;
  echo ' and were gone for ' . $how_long . '<br />';
  echo 'Number of aliens: ' . $how_many . '<br />';
  echo 'Describe them: ' . $alien_description . '<br />';
  echo 'The aliens did this: ' . $what_they_did . '<br />';
  echo 'Was Fang there? ' . $fang_spotted . '<br />';
  echo 'Other comments: ' . $other . '<br />';
  echo 'Your email address is ' . $email;

?>

</body>
</html>

Nothing is being displayed.
So ,Something going wrong in the connect stage, Im working on a local system not a server , and no problem with the form
I go to access my mysql database ,this is what i see
nsnihalsahu@nsnihalsahu-home:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 38
Server version: 5.5.34-0ubuntu0.13.10.1 (Ubuntu)

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SHOW DATABASES
    -> ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| aliendatabase      |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.00 sec)

mysql> USE aliendatabase
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SHOW TABLES;
+-------------------------+
| Tables_in_aliendatabase |
+-------------------------+
| aliens_abduction        |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM aliens_abduction;
Empty set (0.00 sec)

How do I resolve this?

I copied this from php.net, try to use this instead to connect to your db:
For remote:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";

For localhost:
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

echo $mysqli->host_info . "\n";

The code does not print the Arabic text of the database

The code below that I am using will not print text that is of arabic form from the database although the collation of the table is uft8_general_ci and the database is of collation uft8_general_ci.

code:
<?php

        // Create connection
    $con = mysqli_connect("localhost", "", "", "");
    mysqli_set_charset('utf8', $con);

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    // This SQL statement selects ALL from the table 'Locations'
    $sql = "SELECT * FROM Mothakirat";
    mysqli_set_charset('utf8', $sql);

    // Check if there are results
    if ($result = mysqli_query($con, $sql))
    {
        // If so, then create a results array and a temporary one
        // to hold the data
        $resultArray = array();
        $tempArray = array();

        // Loop through each row in the result set
        while ($row = $result->fetch_object())
        {
            // Add each row into our results array
            $tempArray = $row;
            array_push($resultArray, $tempArray);
        }

        // Finally, encode the array to JSON and output the results
        echo htmlentities(json_encode($resultArray));
    }

    // Close connections
    mysqli_close($con);

?>​

How can I get the arabic to print properly?

When working with non-Latin characters in a web based environment, I find there are three points of failure:
1) You need to tell mysql what output to give you when you connect (which you've already done, I think):
mysqli_query('SET CHARACTER SET utf8');

2) You probably need to add
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

into the <head> section in your html.
3) You need to ensure that the font used to display the text has glyphs for the characters you are expecting to see (Times New Roman may not suffice). I have done stuff with Greek and Hebrew and I often find fonts have basic support but not when there are diacritics.