Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Break Down Multidimensional Array


I have a multidimensional array and was wondering how it can be broken down...

Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[intsch_id] => 1
)

[1] => Array
(
[0] => 2
[intsch_id] => 2
)

)

)

And I want to break it down to

Array ( [0] => 1 [intsch_id] => 1, [1] => 2 [intsch_id] => 2) And this is in a dynamic query, so the results won't always be this simple. It will have the same structure as the above multidimensional array.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Multidimensional Array Syntaxt For Preg_split Array Using Submitted Textarea
I have two textarea's called textarea1 and textarea2.  What i did was use preg_split to split the textarea into seperate rows that i could use for analysis like so

$array = preg_split("/[
]?[
]/", $_POST['textarea2'], -1,PREG_SPLIT_NO_EMPTY);
$array2 = preg_split("/[
]?[
]/", $_POST['textarea1'], -1, PREG_SPLIT_NO_EMPTY);

then i used a function created for me by a nice guy on here called get_ending($filepath) which basically stripped off of each peice of text the "http://www" from every URL i put into the textareas

finishing off i wanted to create an array that would input an expression such as:

echo "<a href='$array[1]' target='_blank'><img src='$array2[1]' border='0'>";

into a text area on the next page.  ALL of this works, except that i dont know how to properly loop throught he array so it'll properly insert the text into the textarea on the next page.

For now, all it does is place the array information in the page, rather statically, i would like to run some kind of if then statement that says

"while $array has some kind of text in it, keep running this operation of echoing the following expression adding 1 to the end of the array number"  I hope that makes sense

Any ideas? Code:

Break, Rebuild Array
I have a big form that lists all our products.  Each product has 5 values : Cost, Dist, Special, Resel, & RRP.

The form for updating the values easily as prices can change on a monthly basis.

However when the form is sent as just one big array.  What I need to do is break this down into an array for each product.

There are two ways I have tried to break this down, but I just can't get it to work.

The first way I tried was by sending the model Id with the column name separated by a ',' and then exploding it, but I couldn't quite work out the grouping.

The second way I tried was to send the model Id as it's own readonly input field, but again couldn't work out how to do the count of 6 fields to group them together.  Here is some code for you to get to grips with it. Code:

Passing Array Of Multidimensional Array To Function
How do I pass a part of a multidimensional array to a function. I have the following (in pseudo):

$arrays[m][n]; // filled with values
$chosen = 3;

function doSomething($array) {
 // do something with 1D array
}

This fails:

doSomething($arrays[$chosen]);

Can someone explain to me why? And how to do this right?

Break MultiLine TextBox Into An Array
I need to take a MultiLine TextBox and break it down into an array of the textboxes lines. I know that I can explode a string based on a delimeter and get an array but what would the delimiter be in this case? Thanks, Jeremy

Break A String Into An Array Of Characters
I'm a little bit amazed that Google wasn't able to find me previous
posts on this subject, as I'm sure it's been covered many times before,
but it's possible I'm using all the wrong keywords.

If I want to break a string into an array of individual characters, how
do I do it? I thought explode with an empty delimiter might work, but
it didn't.

Multidimensional Array: See If 1st Key Is Available
I've got an multidimensional array
$ret = $country_code[$countryCode][$langCode];

Now I want to see if $countryCode is even in that array, because if it's
not, it doesn't make many sense to look further for $langCode.

Eg.

$country_code = array('BE' =>
array ('en' => 'Belgium',
'nl' => 'België'),
'NL' =>
array ('en' => 'Netherlands',
'nl' => 'Nederland'),
);

Searching for 'BE' would make sense, but 'LP' wouldn't.

I already tried:
$arr = array($country_code['LP']);
if (sizeof($arr) == 0)
print "LP not found!"

But that doesn't seem to work :-s.

Multidimensional Array
I won't post my exact code since the project I'm working on is HUGE and I'd have to explain it all anyways, but I'll provide examples. Basically, I'm using OOP PHP to build this project... and at one point I have the constructor of 'Class1', calling another method of the same class. In that method, I want to add to a multidimensional array defined in the class itself... in the first position I want to store a string, in the next position, I want to store an instance of another class.

Now, the problem I'm having is that when I try and define the multidimensional array, it takes FOREVER!!!! Literally 25 seconds! All I'm doing is this: PHP Code:

Multidimensional Associated Array
I try to construct an array such that each element of it is another
array returned by the fetch_array_function:
for ( $i = 1; $i<=$n; $i++ )
{
$ar[$i] = mysql_fetch_array( $result );
print "$ar[$i][fieldname]
";
It prints "Array[fieldname]".
If I replace $ar[$i] by $ar everything works fine! Could you pleas...

Multidimensional Array
I have an array that looks like this:

Array
(
   [0] => Array(
      [fieldID] => 001
      [description] => Hi all!)
   [1] => Array (
      [fieldID] => 002
      [description] => It’s me again! )
)
And I want to change it into array that would look like this:
Array
(
   001 => Hi all!
   002 => It’s me again!
)

Is it possible to do it at all?

How To Reference An Array In Multidimensional Array?
How do I reference an array within an array?

$mapped_array = array_map(null, $data_array, $counter_array);

// okay, so now I have an array of 2 arrays - but how do I reference each
array?
// the next two lines fail to give an accurate count
echo "Starting with ".count($mapped_array[0])." elements in
data_array<br>";
echo "Starting with ".count($mapped_array[1])." elements in
counter_array<br><br>";

// now I want to start at the bottom and look for an IP in each line of
data_array
// which I assume is mapped_array[0]
for ( $i=count($mapped_array[0]); $i > 0; $i-- )
{
$data_line = $mapped_array[0][$i];
$data = explode("|", $data_line);
if( in_array($ip, $data) )
{
// if there's a match, element[$i] of both arrays needs to be spliced
out
array_splice($mapped_array,$i,1);
}
}
// again, these next two lines fail to return an accurate count
echo "Ending with ".count($mapped_array[0])." elements in data_array<br>";
echo "Ending with ".count($mapped_array[1])." elements in
counter_array<br><br>";

Is there something about array_map that prevents me from referencing the
arrays within the array?

Problems Using Multidimensional Array
I am trying to understand multidimensional arrays within PHP, and am trying to do the following:

$x[1][1]="test";
$x[1][2]="test2";
$x[2][1]="test3";
$x[2][2]="test4";
print ("$x[1][1] $x[1][2] $x[2][1] $x[2][2]");

but instead of getting the result:
test test2 test3 test4

I am getting:
Array[1] Array[2] Array[1] Array[2]

Can someone please explain why this is happening.

Create A Multidimensional Array From XML Doc
Currently I have the following XML document:

<Programs>
<Program>
<ProductTypeName>30 Yr Fixed</ProductTypeName>
<Rate>6.250</Rate>
<APR>6.274</APR>
<InvestorName>Helos</InvestorName>
<Payment>2832.298</Payment>
</Program>
<Program>
<ProductTypeName>30 Yr Fixed</ProductTypeName>
<Rate>9.250</Rate>
<APR>9.293</APR>
<InvestorName>Avalon</InvestorName>
<Payment>3784.306</Payment>
</Program>
<Program>
<ProductTypeName>5/1 Arm</ProductTypeName>
<Rate>6.375</Rate>
<APR>6.399</APR>
<InvestorName>Carl1</InvestorName>
<Payment>2869.802</Payment>
</Program>
</Programs>

I load it up in a domdocument and iterate through it with the following:

$returns = array();
for($i = 0; $i < $xmlproducttype->length; $i++)
{
$returns[$i]['ProductTypeName'] =
$xmlproducttype->item($i)->nodeValue;
$returns[$i]['InvestorName'] =
$xmlinvestorname->item($i)->nodeValue;
$returns[$i]['Rate'] = $xmlrate->item($i)->nodeValue;
$returns[$i]['APR'] = $xmlapr->item($i)->nodeValue;
$returns[$i]['Payment'] = $xmlpayment->item($i)->nodeValue;
}

Giving me the following style array:

Passing Multidimensional Array Thru The URL
I have an issue with an array that I would to pass to a second php
script; please note that I cannot use session.

I have been looking at the functions : rawurlencode / rawurldecode
urlencode / urldecode but it does not seems to work for my variable

here is an example of variable:

<?
$x=0;
$data[$x][title]="My title";
$data[$x][label]=array("label1","label2","label3");
$data[$x][data]=array(100,150,145);
?>

How can I pass this variable thru an URL?

How To Return A 'sub-array' Of A Multidimensional One
I have a multi-dimensional associative array, and I'm interested in searching the array for a given key, and returning the 'sub-array' or value associated with this key. for example:

Code: $array = array( 'A'=>1, 'B'=>2,
'C'=>ARRAY( 'A2' => 'FRUIT', 'B2' => 'VEGGIE',
'C2' => ARRAY( 'MEAT1' => 'BEEF', 'MEAT2' => 'CHICKEN' ) ) );

I want to retrieve the array under the key 'C2'. I have tried to 'search' the array so that its internal pointer is pointing at this element, then using 'current', but that doens't work: Code:

array_key_exists( 'C2', $array );
var_dump( current( $array ) );

I've also tried a small variation of the above in order to get the reference to C2 rather than a deep copy: Code:

array_key_exists( 'C2', $array );
var_dump( $array[key($array)] );

I would actually prefer to get a reference into the array rather than a copy.. I guess I'm really stuck on the 'search' part of the mutlidimensional array.. Surely there's a better way (built-in function) than iterating every element and comparing the key?

Multidimensional Array Merge
I need one solution for multidimentional array merging option using php. Please send me any samples multidimensional array merging.

Single Array To Multidimensional
I have a string, comma separated, with links and their respective URLs
in it. Example:
Google,http://www.google.com,Yahoo!,http://www.yahoo.com,WikiPedia,http://www.wikipedia.org

etc, etc.

i make an array of this with explode( ',', $string );

now what i wonder is how can i turn this array into something like
this:

$array[0]['name'] = Google
$array[0]['url'] = http://www.google.com
$array[1]['name'] = Yahoo!
$array[1]['url'] = http://www.yahoo.com
$array[2]['name'] = WikiPedia
$array[2]['url'] = http://www.wikipedia.org

I hope/think this is all clear ...

Multidimensional Array Loop
I am trying to loop through a multidimensional array shopping cart stored in a session. I can loop through it ok but the problem is that when the page displays I have two each of the items in the cart. I am looping through with a double foreach.

If I do print "$key: $value"; inside of the second foreach I get the correct display of the items in my cart but then the actual display of the items gives me two of each. Code:

Multidimensional Array Declaration In Php
how to achieve that? it seems php doesn't support it well for a C
programmer?

i hope to use something like:

a[$i][0];

a[$i][1];

a[$i][2];

Checkboxes In A Multidimensional Array
I found this nice code online that does exactly what I want it do to: Emails a form that includes the posted values. I can get the text boxes, text areas, and radio buttons to send; however I cannot for the life of me figure out how to get checkboxes to send. It will only send the last-checked value. I have searched the internet and seen that this is a common problem, but I have not found anything similar to the code that I am using. Code:

Sorting A Multidimensional Array
I Have an array set as so:

$temparr[$i]['score'] = 3.4
$temparr[$i]['id'] = 1
$temparr[$i]['title'] = 'title'

$i loops the array populating it, but when I output the array, i would like to sort it by the 'score' value asc or desc, depending on what i want to show... what is the easiest way of achieving this?

Deleting Multidimensional Array
if i have a multi dimentional array, eg:

$arr[x][y] = '';

and i want to delete the enrite thing, does unset($arr); rowk, or so i have to delet the second arrays, or how do i do it???

Foreach() Multidimensional Array
I did a search for other foreach() problems and cant seem to find a solution that fits my syntax, probably because I'm a newbie. Here is my code:

Jump Out Of A Multidimensional Array?
trying to get out of an array dynamically.

$transport = array('foot', 'bike', 'car', array('test1', 'test2'));
i'm in test2( $transport[3][1] ), how do I go into $transport[3]? Is there a function capable of doing this?

Adding To Multidimensional Array
I'm realtively new to PHP and I'm trying to get my head around a particular issue. I've got an array that looks like this:

$field_array = array (
array (field=>"dist_Company", type=>"text"),
array (field=>"dist_Active", type=>"select", options=>array(array(oname=>"yes", oval=>"1"), array(oname=>"no", oval=>"0"))),
array (field=>"dist_CompanyID", type=>"select"),
array (field=>"dist_Shipping", type=>"text")
);

What I'm trying to figure out is how to add to this array after it's been defined. In this case I'm trying to add the "options" subarray to dist_CompanyID element so that it has options similar to those predefined in the dist_Active element.

I can do it if I specify the index like this:

$field_array[2]['options'][] = array(oname=>"one", oval=>"1");
$field_array[2]['options'][] = array(oname=>"two", oval=>"2");
$field_array[2]['options'][] = array(oname=>"three", oval=>"3");

Is there some elegant way to find the index number for the element containing field=>"dist_CompanyID"?

Sorting A Multidimensional Array On Two Columns
I'm working on some low-tech sort of content managing system. It uses textfiles as a kind of database so the users don't have to install SQL on their server. Now I want to perform some sorting on my files. These are the contents of one of those files.

PageName;Template;Menu;Sub;
Introductie;1;1;1;
Opnemen;1;2;0;
Voorbereidingen;1;2;2;
Kwaliteit;1;1;0;
Blabla;1;2;1;

I first read this file into $someArray with file() and then I parse each row with explode() into columns. So $someArray[2][2] contains the value 2 and $someArray[0][2] contains "Sub".

I want to sort this array on both Menu and Sub and write it back to the file. It should look like this.

PageName;Template;Menu;Sub;
Kwaliteit;1;1;0;
Introductie;1;1;1;
Opnemen;1;2;0;
Blabla;1;2;1;
Voorbereidingen;1;2;2;

I want to make a list of menus and their listed submenus in the proper order, as you can see .

What is the clever way to do this? At this moment I use a loop that sorts the submenu in a loop that finds the right menu in a loop that sorts the menus. No, it's not you, I don't understand it myself anymore. That's because I don't understand most of the array principles and functions.

Copying A Multidimensional Array To $_SESSION
Specifically, is it possible to copy a multidimensional array into the
$_SESSION array - ie a deep clone of all keys and data?

I naively assumed that

$_SESSION["myArray"'] = $myArray ;

would work but it doesn't appear to work. Is there a single function
or assignment I can use, or would I need to use a "foreach" at every
level?

Multidimensional Associatve Array Problem
from a MySQL DB i want to get a multidimensional array that i can loop
through

either key =field name value = array of ENUM options
or array[x][0] =field name, array[x][1]= ENUM options and increment x
inside loop

$q=mysql_query("SHOW FIELDS FROM table" ) or die ("Query failed");

while ($row = mysql_fetch_array($q))
{
//from http://uk.php.net/mysql_fetch_field

echo 'field is '.$row['Field'] . ' type is ' . $row['Type'];
if (ereg('enum.(.*).', $row['Field'], $match))
{
$opts = explode(',', $match[1]);
foreach ($opts as $item)
{$finalResult[] = substr($item, 1, strlen($item)-2);}
}

$array=array ($row['Field'] =>$finalResult[]);

}
gives Fatal error :Cannot use [] for reading in .......

a similar error message when i try a multidimentional array
array[$x][0]=$row['Field']
array[$x][1]=$finalResult[]

Multidimensional Array Using A Recursive Function?
I have to use a recursive function to extract the data from my database. I have scoured the web but can't find any good examples to this challenge. My main obstacle is building the array. The idea is to build an array that could potentially have endless sub arrays.

Multidimensional Array - Search For Relationships
I have a multidimensional array where each sub-array contains just two
entries, which indicates a relationship between those two entries. for
example the first sub-array:
[0] => Array
(
[0] => 30
[1] => 31
)
This states that value 30 is related to 31. I would like to search...

How To Print A Multidimensional Associative Array?
I have the following associative array:

$user["john"]["mozilla"]=1;
$user["john"]["xmms"]=1;
$user["doe"]["mozilla"]=0;
$user["doe"]["office"]=1;
$user["paul"]["mozilla"]=0;
$user["paul"]["xmms"]=1;
$user["paul"]["office"]=1;

How can I print such an associative array using a loop statement like foreach?

Dynamically Adding To Multidimensional Array
$sql= sql query
$i=0;

while
($a2=mysql_fetch_array($a1)){array_push($temparray ,$a2[0],$a2['ad'],$a2[1],$a2[1]);
{
I want this array to be the value of an asssoc. array $results[$i]
$results[$i] =$temparray doesnt work
$results[$i] =$temparray[] doesnt work
$results[$i][] =$temparray doesnt work
$results[$i] =>$temparray doesnt work

then $i++;
}
so what does ?

Multidimensional Array In To A MySQL Table
Trying to load an multidimensional array into a MySQL table with columns as
follows,

level1,level2,level3,illust,item,description,partN o,qua,price,remarks,weight
,size,mass

the array first line is $input[0][level1]Engine
the array secondline is $input[0][level2]Cylinder Head
etc..

A 'foreach' inside a 'foreach' echo of the array gives the following, which
is correct.

0, level1, Engine
0, level2, Cylinder Head
0, level3,
0, illust, 001.pdf
0, item, 1
0, description, Casting
0, partNo, 238356
0, qua, 1
0, price, 1,245.00
0, remarks, This is for the Z350 series
0, weight, 5
0, size, 5x5x5
0, mass, 37
1, level1, Engine
1, level2, Cylinder Head
1, level3,
1, illust, 001.pdf
1, item, 2
1, description, Valve, inlet
1, partNo, 452790
1, qua, 4
1, price, 5.46
1, remarks, This is for the Z350 series
1, weight, 5
1, size, 5x5x5
1, mass, 37
2, level1, Engine
2, level2, Cylinder Head
2, level3,
2, illust, 001.pdf
2, item, 3
2, description, Valve, exhaust
2, partNo, 345436
2, qua, 4
2, price, 5.99
2, remarks, This is for the Z350 series
2, weight, 5
2, size, 5x5x5
2, mass, 37

Implode Multidimensional Array Column...
I tried imploding a column in my MD array like so:

implode(" AND ", $mainarr['br']['sumconditions'])

but this doesnt work returning a bad arguments error message. Does anyone know how to do this?

Searching In Multidimensional Array For A Date
I am using the following function in order to search in multi-dimensional array, as per note added on <a target="_blank" rel=nofollow href="http://it.php.net/array_search">[link]</a>,

[code]
function array_search_recursive($data0, $FinRecSet, $a=0, $nodes_temp=array()){
global $nodes_found;
$a++;
foreach ($FinRecSet as $key1=>$value1) {...

Display Values Of Multidimensional Array
Can anyone help me with a function to display the keys/values of a multidimensional array in a more simpler to read display than that of the standard print_r()?

Create Multidimensional Array Dynamically
I'm already trying for some days to create an array dynamically. I have the following situation:

I have an array of strings.

$data["base:foo:bar"] = "test1";
$data["base:foo2:bar"] = "test2";
$data["base:foo2:bar2"] = "test3";
$data["base:foo:bar2"] = "test4";

This array should be converted in a multidimensional array. The keys for this array are the above keys separated by colons. The dimension of the array varies form situation to situation. Code:

How To Call A Column Instead Of Row In A Multidimensional Array
I have a 2-d array. I want to pass columns from the 2-d array to a file that will graph the columns.

Let's say its called my2darray

I can pass a row with something like my2darray[4]

But I can't pass a specific column with my2darray[][4]

Any help with the syntax or a link to the solution would be helpful. Do I have to use a loop to call a whole column?

Retrieve Multidimensional Array From Mysql?
I am developing a site to sell dvds. Each dvd can have multiple actors, I have created a select query that returns the film information and if there is more than 1 actor associated, more than 1 row is returned. I have tried to use the mysqli_fetch_array function to retrieve all the rows but this only seems to retrieve the first row.

I assumed it would create a multidimensional array but I cannot find a second row. I have tried such things as $row[0][actor_name], $row[1][actor_name] but this does not work.

Array Sort: Multidimensional Arrays?
I'm horrible at arrays. And I'm now using a script that has a lot of neat predefined functions and things that I adore and would never have time to come up with myself.

I'm facing a problem with sorting an array in it though. Can't figure out where to really go in and... determine how to get the info displayed in correct order.

the $tpl->assign_block_vars basically creates a loop out of variables to output using a html template. Now... I want all this sorted by the variable called 'CURRENT'. Can't do ORDER BY in the sql statements since it's nested within a other sql statement call etc. Any help would be apprecciated. Here's the code: .....

PHP Stops Processing On Multidimensional Associative Array
When using a multidimensional associative array to cross-reference data
in a second, single-dimensional array, PHP stops processing data after
a few iterations. Memory usage according to the task manager doesn't
seem to spike and CPU usage only gets as high as 11 to 13 percent. A
sample script is provided below, any help or alternative solutions are
welcome. (By the way, the script below works fine on Linux with the
same version of Apache and PHP. Possibly a PHP configuration issue?)

Confirmation Page With Multidimensional Array Values
I was hoping someone could help a newbie with a script I'm trying to write. I have an HTML form that uses a multidimensional array to generate a select box. The array is as follows: Code:

Searching And Displaying A 'record' In A Multidimensional Array
I have a multidimensional array that fills with data from a database. The array could look like this: Code:

Can I Put A Mysql Query Result Directly Into A Multidimensional Array?
I have two joined tables:

Departments - which contains the department description and a key
Positions - which contains position data

What I'm attempting to achieve is to display the department title in one table cell and then list all the positions associated with that department in the cell under neither the title. I need to generate a table two column table with as many rows as required, depending on the number of departments, which is dynamic.

Do this I'm trying to turn the result of my SQL query into multidimensional array e.g. dept = VioP positions = "designer", "engineer" etc, which I can do then use to generate the table.

I've done a search on the forum and looked around the manual and I'm stumped on how to achieve this, a point in the right direction would be greatly appreciated. The query I'm using is below. PHP Code:

Reading HTML Unordered List Into Multidimensional Array
I have some software (Wordpress, actually) that is sending HTML code of an unordered list when I call a particular function. I want to make that list into a multidimensional array. So something like this: Code:

Break After 5 In Loop
I just tried searching this on the forum but i couldn't find what I needed, i know there is a way to insert a break after a certain number of times a loop has been executed i.e. after every 5 times insert <br> But I've tried but the list is only having two per row:?
PHP Code:             

Php Break Command
I have a while look inside of a for loop and when i use the break command it stops boths loops. I am wondering if there is a way to only have it stop the while look.

Break Apart A Variable
I would like to know how I can break apart a variable. I'm currently
passing the variable $id-hours and I would like to break it down. I would
like to break down to something similar to:

$eid = id (id part of $id-hours)
$ehour = hours (hours part of $id-hours)

Is this possible? I'm new to programming and just trying to get thru it
all.

How Do I Break Up Using Nl2br?
How do I break up this: <?php echo ($row_rsabout['about']);?>

into seperate tables like the nl2br option in PHP:

<?php echo nl2br("LINE ONE LINE TWO");?>

Php Page Break
I am building a form that inserts data into a database and then another user comes and pulls like a report from the database of all the information int he database. I was wondering when i create this report it is actually going to have multiple reports because every record is a a report and I was going to list them all on one screen but i need a way to be able to say where a page breaks for printing.


Copyright © 2005-08 www.BigResource.com, All rights reserved