I have something like this
Array
(
[0] => stdClass Object
(
[CustomerID] => 14
[Email] => joe.blogs#example.com
[LastName] => Blogs
[BirthDayOfMonth] => 29
[Gender] =>
[Occupation] =>
[SendSpecialOffers] => 1
[SendReminderNotes] => 1
)
[1] => stdClass Object
(
[CustomerID] => 1460
[Email] => example#example.com
[LastName] => Example
[BirthDayOfMonth] => 5
[Gender] => F
[Occupation] =>
[SendSpecialOffers] => 1
[SendReminderNotes] => 1
)
);
I would like get Email address of each separated by commas, something like this
'joe.blogs#example', 'example#example.com'
I know i could iterate it through foreach but i got a really big list, is there anyway to do it faster? thanks
Now, how can i remove the indexes based some email addresses?
You can do this with array map and a function but this will also iterate your array
echo implode(',',array_map('getEmail',$array));
function getEmail($obj)
{
return $obj->Email;
}
The simplest solution would indeed be a foreach() to iterate over all the items of your array ; adding, for each item, the email to a another resulting array.
Maybe you could replace the foreach by a call to array_walk(), but it probably wouldn't change much :
You wouldn't loop in PHP, as array_walk is coded in C (could be a bit faster than foreach -- not sure, though)
But a function would be called for each item, instead of just a couple of PHP instructions.
You'd have to benchmark, to see if there is a significant difference in your specific case -- but I personnaly would go for the foreach, without thinking much more.
array_filter is best..see the examples on manual
Related
I have a complex multi-dimensional array that looks something like
[name] => Marko Polo
[description] => New application
[number] => ABCD1234
[loans] => Array
(
[0] => Array
(
[id] => 123
[application_id] => 456
[loan_fees] => Array
(
)
[loan_parts] => Array
(
[0] => Array
(
[id] => 987
[loan_id] => 123
[product_id] => 49788
[product] => Array
(
[id] => 49788
[lender] => MAC
...
I need to create an efficient way of traversing this array and, for example having a set of rules to filter/modify the data.
For example, in the array there is [lender] => MAC, I want to have something like
loans.loan_parts.product.lender.MAC = 'Macquarie'
This would be in a config of sorts such that if the data array changed, it would be simply a matter of changing that dot notation to point to the new location of the lender value.
Using this, I need to filter the lender and modify it to be Macquarie instead of Mac.
I know that a big no-no these days is using too many foreach loops and I've looked into Collections, but because the inner arrays are not named, I don't believe Collections is possible.
As I say, I'd like to avoid the situation of
foreach
foreach
if (is_array())
foreach
eeewww!
How can I execute this in the most efficient manner due to the possible large size of the array and its complexity.
You can use array_walk_recursive with callback that will change behavior according to key of array.
<?php
//can pass variable by reference to change array in function
function handleMAC(&$item, $key)
{
if($key == 'lender'){
$item['MAC'] = 'your value';
}
}
array_walk_recursive($array, 'handleMAC');
?>
Basically, I have an array where each element is a key/value pair of elements, like this:
[myArray] => Array
[0] => Array
[id] => 121
[name] => Value1
[1] => Array
[id] => 125
[name] => Value2
[2] => Array
[id] => 129
[name] => Value3
....
And I want to convert this to:
[myArray] => Array
[121] => Value1
[125] => Value2
[129] => Value3
....
so the 'id' element becomes the key, and the 'name' element becomes the value. Does PHP have something built in (or is there a clever trick) to do this? I'd like to avoid the obvious foreach() loop if there's something cleaner available...
PHP 5.5 has an array_column() function which can do this for you, if you're lucky enough to be running that already. The developer who submitted it also has a forwards-compatible version you can download for earlier versions of PHP.
However, it's pretty easy to roll your own, or just use a foreach loop for the particular case you need.
If you have array_column available you can do:
array_column($myArray, 'name', 'id')
I think the foreach is the much better option, though.
After several hours of messing, sweating and pulling my hair out I'm still unable to access these values. I want to loop through the first level of arrays, and that's simple enough with a basic 'foreach' loop but I can't seem to get to the '['suitability']' array on the second sub array. I've looked around but can't seem to get anything other than really basic array tutorials which don't seem to delve to far into looping.
I'm trying to access the values in the nested/sub array ie '['Species_name']'.
I don't want to use associative keys as the sorting is a bit of an issue.
Array
(
[0] => Array
(
[id] => 1
[name] => Bradeley Hall Pool
[postcode] => CW1 5QN
[lat] => 53.10213
[lon] => -2.41069
[size] => 1.60
[pegs] => 21
[distance] => 26.6
)
[1] => Array
(
[id] => 2
[name] => Farm Pool
[postcode] => CW9 6JQ
[lat] => 53.320502
[lon] => -2.549049
[size] => 0.88
[pegs] => 8
[distance] => 15.4
[suitability] => Array
(
[0] => Array
(
[fk_water_id] => 2
[fk_species_id] => 4
[species_name] => Barbel
[species_rating] => 1
[record_id] => 1
[weight_kg] => 2.721554
[length_cm] => 40
[height_cm] => 30
)
)
)
)
The thing that is probably tripping you up is that suitability is an array of arrays not just an array so in an example where you want to get the species_name property of the first second top level element you would use something like
$array[1]["suitability"][0]["species_name"];
It's worth noting that your first array does not contain a "suitability" value so that would not be able to be accessed. In a foreach loop you could use a construct similar to this:
foreach($array as $value){
if (isset($value["suitability"])){
echo $value["suitability"][0]["species_name"];
}
}
For getting nested element value from multidimensional array (with optional fallback to default value) you can use get method from this array library:
Arr::get($array, "$index1.suitability.$index2.species_name")
// Or using array of keys
Arr::get($array, [$index1, 'suitability', $index2, 'species_name'])
You may take a look at PHP: RecursiveArrayIterator class
This allow you to iterate over multiples nested ArrayIterator. If you're not using any ArrayIterator, then you should consider to try them.
Iracicot's answer helped me find my way towards accessing the values of a recursive array using the RecursiveIterator class as below. My solution ended up using the even more useful RecursiveIteratorIterator class as per http://php.net/manual/en/class.recursiveiteratoriterator.php. Please bear in the mind the very useful fact that the end product is a flattened array which I personally found much easier to work with.
<table style="border:2px;">
<tr>
<th>Time</th>
<th>Service Number</th>
<th>Destination</th>
</tr>
<?php
foreach($stops as $buses){
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($buses));
$bus = (iterator_to_array($iterator,true));
print('<tr><td>'.$bus['AimedDepartureTime'].'</td><td>'.$bus['PublishedLineName'].'</td><td>'.$bus['DirectionName'].'</td></tr>');
}
?>
</table>
I'm building a 3 page submission form, and I'd quite like all of the $_POST results to be stored in a single session variable.
So page 1 starts by setting up the array and adding the first lot of post data:
$_SESSION['results'] = array();
$_SESSION['results'] = $_POST // first lot of post data
This works great and returns an array like:
Array
(
[name] => bob
[address] => 1 foobar way
[age] => 100
)
So when I get the resuts from page 2, I want to simply append them to the existing array without invoking a new array+key
array_push($_SESSION['results'], $_POST); //second lot of post data
To get something like this:
Array
(
[name] => bob
[address] => 1 foobar way
[age] => 100
[job] => rubbish php dev
[salary] => 1000
)
But instead I get:
Array
(
[name] => bob
[address] => 1 foobar way
[age] => 100
[0] => Array
(
[job] => rubbish php dev
[salary] => 1000
)
)
Even more annoying is that I'm sure I had this working properly before I tweaked the code. What am I doing wrong?
You can also use the + operator:
$combined = $_SESSION['results'] + $_POST;
array_merge() is the function you're after.
array_merge() is your answer see http://php.net/manual/en/function.array-merge.php
You have to use array_merge(), look at this: array_merge()
I have an array like this:
Array
(
[0] => Array
(
[id] => 68
[type] => onetype
[type_id] => 131
[name] => name1
)
[1] => Array
(
[id] => 32
[type] => anothertype
[type_id] => 101
[name] => name2
)
)
I need to remove some arrays from it if the users has permissions or not to see that kind of type. I am thinking on doing it with a for each, and do the needed ifs inside it to remove or let it as it.
My question is: What's the most efficent way to do this? The array will have no more than 100 records. But several users will request it and do the filtering over and over.
use this 1 simple and easy
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
Use in_array() function so that you could find the array that you would want to remove.
Then use unset() function to unset the array or variable that you would want to remove from your existing array.
On this way, you don't need to loop your array over and over.
I think you understand the basics of PHP and stripping the array.
What you could do after stripping the array store it in a session for re-use after a page-refresh or loading of a different page. That way, you only have to do it once.
See: http://www.php.net/manual/en/function.session-start.php