I'm trying to loop through a multidimensional array with foreach but sometimes there's 5 dimensions and sometimes there's 2, but I need to foreach every array. Here is an example:
array(16) {
["id"]=>
string(2) "1"
["name"]=>
string(1) "Bob"
["job"]=>
array(2) {
[0]=>
string(8) "software"
[1]=>
string(7) "plumber"
}
["kids"]=>
array(2) {
[1]=>
array(2) {
[0]=>
string(4) "Jane"
[1]=>
string(4) "girl"
}
[2]=>
array(2) {
[0]=>
string(3) "Sam"
[1]=>
string(4) "boy"
[2] => array(2) {
[0]=>
string(3) "123"
[1]=>
string(11) "Main Street"
}
}
}
}
you get the point.... but imagine if I had a dimension of 10 in the array. How can I dynamically loop through them and do trim() to each value in the whole array?
Here is what I have so far:
foreach ($array as $key => $value) {
$array[$key] = trim($value);
}
but I need it to go deeper into an array if there is an array and perform trim to all values in my $array.
I am trying to loop through array of arrays in php. Usually get stalked with complex array sometimes but I need your kind assistance with this.
var_dump($array) produced the array below:
$arrayVal = array(6) {
["item_id"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
["request_explanation"]=>
array(2) {
[0]=>
string(7) "Welcome"
[1]=>
string(11) "Hello World"
}
["quantity"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "4"
}
["unit_cost"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "3"
}
["total_cost"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["supporting_document"]=>
string(0) ""
}
My database table:
I want to be able to save each of the value in that array into the table above. Thanks for helping me.
Use the indexes of one of the sub-arrays to access all the other sub-arrays:
foreach ($array['item_id'] as $i => $item_id) {
$request_explanation = $array['request_explanation'][$i];
$quantity = $array['quantity'][$i];
// repeat this for all the columns
// Now you can insert all these variables into the database
}
Use a loop to build 2 separate arrays:
foreach($array['ExpensesList'] as $index => $val){
$array1[$index] = $array['ExpensesList'][$index][0];
$array2[$index] = $array['ExpensesList'][$index][1];
}
Then insert each array into your database individually.
This will not work if any sub array contains an index at 2, so this is explicitly for the example structure you provided.
Below I've appended the $var_dump of an array that I've created through user-actions involving an HTML form.
I'm certainly willing to consider other strategies for achieving the final effect (and I'm not, to be honest, positive that it would not be better achieved via WordPress functions, since that's the environment this problem originates in), but the simplest answer would be to take the array described below, get rid of the "NULL" responses, then alphabetize ALL of the remaining sets by last name (which I originally put first since in an earlier, similar version of the same task it happened to make the final sort a snap).
The output will appear on a sign-in list at an event, with first column numbered, second column showing first name - last name with company underneath, a signature line, a line describing the "ticket type," and the ticket price.
SO, just to make it easy to picture:
No. FIRST/LAST/company SIGNATURE TICKET TYPE PRICE
(#) Amy Abrams, Carolco ......... Member $5
The natural way to do it, for me, was to produce an HTML table in which each variable, located by some kind of index, is output via PHP. I've had some versions that ALMOST worked, involving foreach loops at the very limits of my understanding of array manipulation.
I suspect that the person who can answer my question could write what I've tried in his or her sleep, but, just to give a flavor without dumping in a bunch more code... having gotten the below array in a variable called $meta, I could foreach through it foreach ($meta as $reservation), then print some of the variables, but not all of them, and not all in right order, with $reservation['first_name'][0], for example. I tried dropping an $i in place of the [0], and fooling around with other key/value/iterator combinations, but at this point I'm just iterating through my own internal array of ca. 999 wrong vs 1 right solutions.
I know this is a common type of question, but in poring through the threads here, I have yet to find a version like this one directly answered.
array(8) {
[0]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[1]=>
array(5) {
["last_name"]=>
array(3) {
[0]=>
string(6) "Winger"
[1]=>
string(6) "Dinger"
[2]=>
string(7) "Stassen"
}
["first_name"]=>
array(3) {
[0]=>
string(5) "Debra"
[1]=>
string(3) "Hum"
[2]=>
string(6) "Harold"
}
["price"]=>
array(3) {
[0]=>
string(2) "10"
[1]=>
string(2) "10"
[2]=>
string(4) "6.35"
}
["company"]=>
array(3) {
[0]=>
string(14) "Post Data Test"
[1]=>
string(14) "Post Data Test"
[2]=>
string(14) "Post Data Test"
}
["ticket_type"]=>
array(3) {
[0]=>
string(16) "Shippable Ticket"
[1]=>
string(16) "Shippable Ticket"
[2]=>
string(14) "Special Ticket"
}
}
[2]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[3]=>
array(5) {
["last_name"]=>
array(3) {
[0]=>
string(9) "Mightwork"
[1]=>
string(1) "u"
[2]=>
string(3) "why"
}
["first_name"]=>
array(3) {
[0]=>
string(9) "Bizarrely"
[1]=>
string(11) "whatsamatta"
[2]=>
string(8) "done no "
}
["price"]=>
array(3) {
[0]=>
string(1) "5"
[1]=>
string(4) "12.7"
[2]=>
string(4) "12.7"
}
["company"]=>
array(3) {
[0]=>
string(13) "Get Data Test"
[1]=>
string(13) "Get Data Test"
[2]=>
string(13) "Get Data Test"
}
["ticket_type"]=>
array(3) {
[0]=>
string(16) "Shippable Ticket"
[1]=>
string(14) "Special Ticket"
[2]=>
string(14) "Special Ticket"
}
}
[4]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[5]=>
array(5) {
["last_name"]=>
array(2) {
[0]=>
string(7) "Marlatt"
[1]=>
string(7) "Stewart"
}
["first_name"]=>
array(2) {
[0]=>
string(4) "Jeff"
[1]=>
string(3) "Al "
}
["price"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["company"]=>
array(2) {
[0]=>
string(23) "Jeff Marlatt Consulting"
[1]=>
string(23) "Jeff Marlatt Consulting"
}
["ticket_type"]=>
array(2) {
[0]=>
string(16) "testing defaults"
[1]=>
string(16) "testing defaults"
}
}
[6]=>
array(5) {
["last_name"]=>
NULL
["first_name"]=>
NULL
["price"]=>
NULL
["company"]=>
NULL
["ticket_type"]=>
NULL
}
[7]=>
array(5) {
["last_name"]=>
array(3) {
[0]=>
string(10) "Flintstone"
[1]=>
string(10) "Flintstone"
[2]=>
string(6) "Rubble"
}
["first_name"]=>
array(3) {
[0]=>
string(4) "Fred"
[1]=>
string(5) "Wilma"
[2]=>
string(5) "Betty"
}
["price"]=>
array(3) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
[2]=>
string(1) "0"
}
["company"]=>
array(3) {
[0]=>
string(23) "Jeff Marlatt Consulting"
[1]=>
string(23) "Jeff Marlatt Consulting"
[2]=>
string(23) "Jeff Marlatt Consulting"
}
["ticket_type"]=>
array(3) {
[0]=>
string(6) "MEMBER"
[1]=>
string(6) "MEMBER"
[2]=>
string(6) "MEMBER"
}
}
}
So firstly you have built your array in a very strange way. If all you want to do is output all the different guests it would be better to create a new element in your array for each guest, that way you could sort them and iterate them with ease. However as you have asked the question I will give you a solution...
To be able to sort your array we need to take your array and turn it into the array I described above. This array will look something like this...
array(
[0] => array(
[last_name] => 'blah',
[first_name] => 'blah',
[company] => 'blah',
[ticket_type] => 'blah',
[price] => 'blah',
),
[1] => array(
[last_name] => 'blah',
[first_name] => 'blah',
[company] => 'blah',
[ticket_type] => 'blah',
[price] => 'blah',
),
etc...
);
Then you can use the PHP function usort() to sort your multidimensional array by the value of the subarrays. Here's my solution...
//This function is used by usort() to sort the guests array by last name
//UPDATE: this function is now case insensitive and sorts on first name secondarily
function sort_by_last_name( $a, $b ) {
//Convert values to lowercase to make sorting case insensitive
$a_firstname = strtolower( $a['first_name'] );
$a_lastname = strtolower( $a['last_name'] );
$b_firstname = strtolower( $b['first_name'] );
$b_lastname = strtolower( $b['last_name'] );
//If the last names are the same sort by first name
if( $a_lastname == $b_lastname ) {
return strcmp( $a_firstname, $b_firstname );
}
return strcmp( $a_lastname, $b_lastname );
}
//This function returns a nicely formatted array of
//reservations sorted alphabetically by last name
function sort_reservations( $reservations ) {
//If reservations is empty get outta there
if( !$reservations || !is_array( $reservations ) ) { return false; }
//Create an empty array to store the formatted data
$guests = array();
//Loop through reservations
foreach ( $reservations as $res ) {
//If the reservation is empty skip onto the next one
if( !$res['last_name'] ) { continue; }
//See how many people are in the reservation
$count = count( $res['last_name'] );
//iterate through reservation n number of times
for( $i = 0; $i <= $count - 1; $i++ ) {
//Add reservations to the nsorted guests array
$guests[] = array(
'last_name' => $res['last_name'][$i],
'first_name' => $res['first_name'][$i],
'price' => $res['price'][$i],
'company' => $res['company'][$i],
'ticket_type' => $res['ticket_type'][$i]
);
}
}
//sort gusts by last name alphabetically
usort( $guests, 'sort_by_last_name' );
//Return our nicely formatted and sorted array
return $guests;
}
Now for example your unformatted array of reservations is stored in a variable $reservations you can sort it by using...
$guests = sort_reservations( $reservations );
Then you build your table in html and for each table row you can iterate over this array printing out a new guest to every row. like this....
<?php $guests = sort_reservations( $reservations ); ?>
<table>
<thead>
<tr>
<th class="firstname">First Name</th>
<th class="lastname">Last Name</th>
<th class="company">Company</th>
<th class="tickettype">Ticket Type</th>
<th class="price">Price</th>
</tr>
</thead>
<tbody>
<?php foreach( $guests as $guest ) { ?>
<tr>
<td class="firstname"><?php echo $guest['first_name']; ?></td>
<td class="lastname"><?php echo $guest['last_name']; ?></td>
<td class="company"><?php echo $guest['company']; ?></td>
<td class="tickettype"><?php echo $guest['ticket_type']; ?></td>
<td class="price">£<?php echo round( $guest['price'], 2 ); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
And bob's your uncle, you've got a table of guests sorted alphabetically by their surnames.
Hope that helps
Dan
Good day.
Code:
array(4) {
[0]=> array(1) {
[0]=> array(3) {
[0]=> string(11) "art_7880" [1]=> string(1) "1" [2]=> int(2950)
}
[1]=> array(3) {
[0]=> string(8) "art_7880" [1]=> string(1) "1" [2]=> int(2955)
}
[2]=> array(3) {
[0]=> string(8) "art_7880" [1]=> string(1) "1" [2]=> int(1335)
}
[3]=> array(3) {
[0]=> string(8) "art_7883" [1]=> string(1) "1" [2]=> int(4335)
}
}
I get array unique elements:
$arr_uniq = array();
foreach ($all_array as $keys => $elms ) {
if(!in_array($elms[0], $arr_uniq)) {
$arr_uniq[] = $elms[0];
}
}
Tell me pleasse how to get a count each unique element in the general array?
result should been next:
art_7880 - 3
art_7883 - 1
Assuming $all_array is subarray of your main array in your var_dump snipett, the general idea is
$result = array();
foreach ($all_array as $elms)
$result[$elms[0]]++;
array_count_values()
http://php.net/array_count_values
You should be able to easily apply this function.
i have the following array:
["addToCart"]=>
array(3) {
[1]=>
array(5) {
["aantal"]=>
int(1)
["film_id"]=>
string(1) "1"
["zaal_id"]=>
string(1) "1"
["dag"]=>
string(7) "maandag"
["seats"]=>
array(4) {
[0]=>
string(2) "67"
[1]=>
string(2) "68"
[2]=>
string(2) "69"
[3]=>
string(2) "70"
}
}
You can see that i have an array called "seats" inside the "addToCart" array.There are 4 items in the "seats" array.
what i would like to have is 4 separate arrays, they should all have the same content but each of them needs to have 1 value of "seats".
I'm not sure I got exactly what you're looking to do, but this would result in an array of arrays where each has only one seat:
$seatArrays = array();
foreach ($addToCart as $arr)
{
foreach ($arr["seats"] as $seat)
{
$seatArr = $arr; // Copy the original array
$seatArr["seats"] = $seat; // Replace the "seats" subarray with the current seat
$seatArrays[] = $seatArr;
}
}