Welcome Guest, Not a member yet? Register   Sign In
Array problem
#1

[eluser]vivar[/eluser]
Hi,

I usually find my answers just by lurking here on the forums but today I actually have a question to ask.

I have a database table with a column that holds a list of names. I actually even added a column called sections which holds the first letter of each name because I was having difficulty with this. I am trying to place the data in an array that resembles the output below:

<dict>
<key>A</key>
<array>
<string>Aaliyah</string>
<string>Aaron</string>
<string>Abagail</string>
</array>
<key>B</key>
<array>
<string>Bailee</string>
<string>Bailey</string>
<string>Bailey</string>
</array>

.......................................

<key>Y</key>
<array>
<string>Yadira</string>
<string>Yael</string>
<string>Yahir</string>
</array>
<key>Z</key>
<array>
<string>Zachariah</string>
<string>Zachary</string>
<string>Zachery</string>
</array>
</dict>

The reason I need the data setup in this fashion is because it is being fed to another application via JSON. I am having no success returning my data in a key / value list. I may be looking at this the wrong way. I wrote a quick loop to visualize the results:


Code:
&lt;?php

// see if our query returned any data before processing (query is taken care of in the model)
if (count($adminUnit)){

        // $myLetter is an array returned from my Model (connecting to MySQL)
        // it holds the following data: A,B,C,D etc.
        // loop through each letter that has a section in the database
    foreach ($myLetter as $id => $letter){
        echo $letter['section'];
        echo '<br/>';

                // $adminUnit is an array returned from my Model (connecting to MySQL)
                // it holds a list of names and a section column (A, B, C, D etc.)
                // loop through $adminUnit
        foreach ($adminUnit as $key => $list){
                        // now print out the data IF the section matches the outer loops section (ie. 'A' =='A')
            if (strtoupper( $list['section']) == $letter['section']){
                echo $list['name'];
                echo '<br/>';
            }
        }  
    }
}

?&gt;

That is as far as I have gotten. I'm not sure how to 'build' the results into a key/value array like the dictionary I displayed at the top of the post.

Basically I would need a dictionary of 26 arrays (the alphabet). The key in each dictionary entry is 'A' to 'Z', and the objectForKey is an array (which contains all the names that begin with that letter).

Any help / guidance / suggestions would be greatly appreciated.
#2

[eluser]jcavard[/eluser]
[quote author="vivar" date="1249513348"]Hi,

I usually find my answers just by lurking here on the forums but today I actually have a question to ask.

I have a database table with a column that holds a list of names. I actually even added a column called sections which holds the first letter of each name because I was having difficulty with this. I am trying to place the data in an array that resembles the output below:

<dict>
<key>A</key>
<array>
<string>Aaliyah</string>
<string>Aaron</string>
<string>Abagail</string>
</array>
<key>B</key>
<array>
<string>Bailee</string>
<string>Bailey</string>
<string>Bailey</string>
</array>

.......................................

<key>Y</key>
<array>
<string>Yadira</string>
<string>Yael</string>
<string>Yahir</string>
</array>
<key>Z</key>
<array>
<string>Zachariah</string>
<string>Zachary</string>
<string>Zachery</string>
</array>
</dict>

The reason I need the data setup in this fashion is because it is being fed to another application via JSON. I am having no success returning my data in a key / value list. I may be looking at this the wrong way. I wrote a quick loop to visualize the results:


Code:
&lt;?php

// see if our query returned any data before processing (query is taken care of in the model)
if (count($adminUnit)){

        // $myLetter is an array returned from my Model (connecting to MySQL)
        // it holds the following data: A,B,C,D etc.
        // loop through each letter that has a section in the database
    foreach ($myLetter as $id => $letter){
        echo $letter['section'];
        echo '<br/>';

                // $adminUnit is an array returned from my Model (connecting to MySQL)
                // it holds a list of names and a section column (A, B, C, D etc.)
                // loop through $adminUnit
        foreach ($adminUnit as $key => $list){
                        // now print out the data IF the section matches the outer loops section (ie. 'A' =='A')
            if (strtoupper( $list['section']) == $letter['section']){
                echo $list['name'];
                echo '<br/>';
            }
        }  
    }
}

?&gt;

That is as far as I have gotten. I'm not sure how to 'build' the results into a key/value array like the dictionary I displayed at the top of the post.

Basically I would need a dictionary of 26 arrays (the alphabet). The key in each dictionary entry is 'A' to 'Z', and the objectForKey is an array (which contains all the names that begin with that letter).

Any help / guidance / suggestions would be greatly appreciated.[/quote]

I am not sure I get it, but here it goes...
let's say you have a query that returns 2 fields:
- category (A, B...)
- name (Aaron, Baylee...)

You could loop through the result and build an array that way
Code:
$this->db->select('category, name');
$handle = $this->db->get('myTable');

$json = array();

foreach($handle->result as $row)
{
  $json[$row->category][] = $row->name;
}
This would output an array with that sturcture, something in the likes of
Code:
$json['A']['Aaliyah'];
$json['A']['Aaron'];
$json['A']['Abagail'];
$json['B']['Bailee'];
$json['B']['Bailey'];
$json['B']['Bailey'];
$json['Y']['Yadira'];
$json['Y']['Yael'];
$json['Y']['Yahir'];
$json['Z']['Zachariah'];
$json['Z']['Zachary'];
$json['Z']['Zachery'];

Also, you don't need that 'category' column in you table. It would be redundant information. You can create it at 'runtime' with a select like this instead:
Code:
$this->db->select('name');
$this->db->select('UPPER(SUBSTRING(name, 0, 1)) as category'); //this will select the first letter of the name and store it in a row named category - note: drop the current category column or rename it otherwise mysql will throw some err on the column name
$this->db->order_by('name', 'ASC');
$handle = $this->db->get('myTable');
I am at work right now, so I haven't had time to test the code, but it should do the trick. let me know, hope it helped.
#3

[eluser]jcavard[/eluser]
One more thing, I noticed the structure you pasted (the dictionary) is XML. That's not JSON. If you need to format the resulting array into XML, look up on google for some custom function

like this one
Code:
&lt;?php
function array2xml($buffer) {
    $xml  = "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n";
    $xml .= "<service version=\"1.0\">\n";
    foreach($buffer as $val) {
        $xml .= "    <document>\n";
        
        foreach ($val as $key => $value) {
            $xml .= "        <{$key}>".utf8_encode($value)."</{$key}>\n";
        }
        
        $xml .= "    </document>\n";
    }
    $xml .= "</service>\n";
    
    return $xml;
}


// exemple d'utilisation

$array = array(
                array("id" => "1",
                      "pseudo" => "mq",
                      "name" => "marc"),
                array("id" => "2",
                      "pseudo" => "poppy",
                      "name" => "axel")
            );

$xml = array2xml($array);
?&gt;

or if it's really JSON, then you can use native PHP json_encode()/json_decode() function.
#4

[eluser]vivar[/eluser]
Hi,

Yes, the dictionary is XML. The app I am sending the data to is actually a native iPhone app and I have been using JSON in favor of XML for development.

Thanks for the help.
#5

[eluser]jcavard[/eluser]
did it solve your problem?
#6

[eluser]vivar[/eluser]
Hi,

I think it will.

I'm looking at formatting my data with XML in this case and basically get the exact results as the dictionary I posted above. This should be achievable, right?
#7

[eluser]vivar[/eluser]
Hi,

Using your array2xml I am very close.

By the way, I should have mentioned that I am querying a view in MySQL (I am very used to using ORACLE) so the category column is just generated using a substring function in SQL at query time.

Anyway, this is the data I have now in xml with the few names I have added to the db:
Code:
&lt;?xml version="1.0" encoding="utf-8"?&gt;
<service version="1.0">
    <document>
        <0>Aaliyah</0>
        <1>Aaron</1>
        <2>Abagail</2>
    </document>
    <document>
        <0>Carl</0>
        <1>Chris</1>
    </document>
    <document>
        <0>Oliver</0>
    </document>
    <document>
        <0>George</0>
    </document>
    <document>
        <0>Iggy</0>
        <1>Isabelle</1>
    </document>
    <document>
        <0>Paul</0>
        <1>Peter</1>
    </document>
    <document>
        <0>Sam</0>
        <1>Scott</1>
        <2>Shawn</2>
    </document>
</service>

I am just missing the actual key (ie. 'A' etc.) and I'm not sure where add this to the code so it is included in the XML. I can see the section letter in the $result array:
Code:
Array ( [A] => Array ( [0] =>Aaliyah [1] => Aaron [2] => Abagail ) // etc.

So I know that the required data is there.

Thanks for your help.




Theme © iAndrew 2016 - Forum software by © MyBB