i am having problems in exploding array and working with it.
i have array of serial numbers for books categorized as read and unread books.
when ever there is book that is read i place read in array after that serial number as follow.
array(
"1234567890","read",
"2345678901","read",
"2345678901",
"2345678901",
"1234561231",
"3333333333","read",
"3333333333"
)
status is unread for all others and in out put i want to loop through the array give me this result.
1234567890: 0 unread, 1 read
2345678901: 2 unread, 1 read
1234561231: 1 unread, 0 read
3333333333: 1 unread, 1 read
any help will be appreciated .
In the first time that array you have is not build in the best way, better would be :
$arr = array(
"1234567890","read",
"2345678901","read",
"2345678901","unread"
)
but you can do this:
$idx=count($arr);
$collector=array();
for($i=0;$i<$idx;$i++){
if($arr[$i]==='read') continue;
if(!isset($collector[$arr[$i]])){
$collector[$arr[$i]]=array(0,0);#array(read,unread)
}
if($arr[$i+1]==='read'){
$collector[$arr[$i]][0]++;
} else {
$collector[$arr[$i]][1]++;
}
}
#print it
foreach($collector as $id => $data){
print "$id: {$data[0]} read , {$data[1]} unread<br>".PHP_EOL;
}
But better try to collect the data in a better way!!!
Use Multidimensional array instead:
<?php
$arrBooks = array(
"1234567890" => array(
"read"=>'1',
"unread"=>'0'),
);
foreach ($arrBooks as $obj_key =>$book)
{
echo "$obj_key:<br>";
foreach ($book as $key=>$value){
echo "$key: $value<br>";
}
echo "<br>";
}
This way you can easily loop through the keys and get the data accordingly.
If you wish to update the arrays as well, here is the piece of code:
foreach ($arrBooks as $obj_key =>$book)
{
if($obj_key=="1234567890")
{
foreach ($book as $key=>$value){
if($key=="read")
{
$value+=1;
}
echo "$key: $value<br>";
}
}
}
Related
The problem I am getting is when I loop through the multidimensional array, once I get to skills in the multidimensional array, it prints out:
Andrew Wiley
30
Game Designer
72000
Array
C++ Level Design Leadership
It's printing out both Array and C++ Level Design Leadership.
How do I remove the output of Array and replace it with the skills C++ Level Design Leadership without printing both?
$students = [
Andrew => [
fullName => Andrew Wiley,
age => 30,
jobTitle => Game Designer,
Salary => 72000,
skills => [C++, Level Design, Leadership]
]
];
foreach($students[Andrew] as $student) {
echo $student . <br>;
if($student == $students[Andrew][skills]) {
foreach($students[Andrew][skills] as $skill) {
echo $skill;
}
}
};
You can use a recursive function.
function printVariables($array,$level=1){
foreach($array as $value){
if(is_array($value)){
$level++;
printVariables($value,$level);
}else{
echo $level <= 2 ? "$value\n" : "$value ";
}
}
}
printVariables($students);
Or serialize it...
foreach($students as $student){
echo json_encode($student,JSON_PRETTY_PRINT);
}
Update your foreach like so:
foreach($students['Andrew'] as $student) {
echo $student . <br>;
if($student === $students['Andrew']['skills']
&& is_array($students['Andrew']['skills'])
&& count($students['Andrew']['skills']) > 0) {
echo implode(", ",$students['Andrew']['skills']);
}
}
Output:
C++, Level Design, Leadership
What this does:
If statement checks if it is equal,
Then checks if it is an array
Then checks that the array is not empty
Before finally joining up all the array elements in to a string and outputting that string with echo.
Also note the quotes around the array keys
I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.
I am trying to solve the following problem:
Note I am new to programming and PHP and working through SAMS PHP, MySQL and Apache (Julie C. Meloni).
There is an exercise where a multidimensional array has to be created. The outer array is an associative array listing the genres of movies. The genre arrays list movies of that genre. You are then asked to print out a list of genres with the list of films associated with that genre.
My code:
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
$gKeys = array_keys($genres);
foreach ($gKeys as $genre) {
print $genre."<br/>";
}
?>
This works and prints out:
Science Fiction
Drama
Crime
Here's where I am running into a wall. When I try adding another foreach loop after
print $genre;
no results appear in the browser (except results of first loop). I have tried everything. For example:
starting by using the array_value() function applied to $genre and then try a foreach on the array returned.
In the textbook there is also a while (list($x) = ($y)) mechanism mentioned.
I thoroughly re-read the array chapter and have looked elsewhere to no avail.
perhaps I have structured the multidimensional array incorrectly? Do the second dimensional arrays need to be associative arrays also for consistency?
Your array is structured correctly. You're taking wrong array (array of just the keys) and adding another foreach loop after print $genre; hence it is not working.
No, it is not required for second dimensional arrays to be associative arrays as well.
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
foreach ($genres as $genre => $movies)
{
print $genre . " - <br/>";
foreach ($movies as $movie)
{
print $movie . "<br/>";
}
print "</br>";
}
?>
Wait! Why are you doing:
$gKeys = array_keys($genres);
This just gives you a single array of keys.
Do your first loop on $genres, then inside:
foreach ($genre as $key=>$subgenre)
{
//do stuff here
}
foreach ($genres as $genrekey => $genrevalue) {
print $genrekey."<br/>";
foreach ($genrevalue as $value) {
print $value."<br/>";
}
}
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$gKeys = multiarray_keys($genres);
echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
Your outer array is an associative array with genres as keys.
To print out movies of that genre (the subarrays), use another foreach as follows:
print "<ul>";
foreach ($genres as $genre => $movies) {
print "<li>".$genre."<ul>";
foreach ($movies as $movie) {
print "<li>".$movie."</li>";
}
print "</ul></li>";
}
print "</ul>";
If you need this for seeing what data goes in an array for debugging purposes you could use PHPs var_export(), var_dump(), print_r() only to make sure the data is getting populated as you want it to. Otherwise if you want to show it in production you could do some like this:
foreach($multiDimentinalArray as $key => $value):
if(is_array($value)):
foreach($value as $k => $val):
print " $key.$k => $val";
else:
print "$key => $value";
endif;
endforeach;
I have an array and it has two arrays inside of it...I am able to access what I want for the first row by doing this...
print_r( $_SESSION['shopcart']['cart']['qty']);
How would I write that in a foreach?
Thanks,
J
foreach($_SESSION['shopcart']['cart']['qty'] as $value) {
echo $value;
}
you would do something like this:
to dump the array: $_SESSION['shopcart']['cart']
foreach($_SESSION['shopcart']['cart'] as $key=>$value){
echo $key." => ".$value."<br/>";
}
If you want to iterate through multiple dimensions, you can nest foreach as follows:
foreach($_SESSION['shopcart'] as $cart) {
foreach ($cart as $qty) {
// do something
}
}
Though I'd need a little more information about the array structure and what you really want to do in order to provide usable code, this is probably in the right ballpark.
I would recommend you you do do like this:
foreach($_SESSION['shopcart'] as $key=>$value){
if(is_array( $value ) ){
foreach($value => k1 => $v1){
//do something here if array
echo $k1." => ".$v1."<br/>";
}
}else{
//do something here if not array
}
}
I have 2 arrays, both from a SQL query, each from a different database. Since it's not possible to merge these 2 SQL queries into 1 query to get 1 array (due to some restrictions), I am forced to combine the 2 arrays. Problem is, I can't seem to get this working.
This is array 1:
echo '<ul id="friends">';
foreach($result as $friend => $value)
{
echo '<li><img src="'.$value['pic_square'].'" alt="" />'.$value['uid'].' ' . $value['name'] . '</li>';
}
echo '</ul>';
And will output:
picture 12345 Dave
picture 67890 Mike
Etc
This is array 2:
echo '<ul id="friends">';
while($value = mysql_fetch_array($query))
{
echo '<li> '.$value['fbid'] .' '. $value['userphone'] .'</li>';
}
echo '</ul>';
And will output:
12345 020-12345
67890 020-56789
Etc
What do I need? I want to merge these 2 arrays so that the phonenr from array 2 will be added behind the username from array 1.
Example what the output should look like:
picture Dave 020-12345
picture Mike 020-56789
Etc
fbid and uid are the id's to link each other, but are not shown in the combined array.
Hope someone knows how to do this!
Kind regards,
Maurice
This is the simplest and most efficient way I could think of doing it. The foreach loop iterates through your first array and basically add new key/value pairs using the "uid" as the key. This will enable you to easily find them when you loop through the second query's results.
<?php
// First query.
foreach ( $result as $key => $value )
{
// Add a new key/value pair in the array using the "uid" as the key and $value as the value.
$result[$value['uid']] = $value;
// Remove the previous key/value pair value.
unset($result[$key]);
}
// Second query.
while ( $value = mysql_fetch_array($query) )
echo sprintf('<li>%s %s %s</li>', $result[$value['fbid']]['pic_square'], $result[$value['fbid']]['name'], $value['userphone']);
As the array collection names are different (different column name) I am not sure direct merging will work.
$result = array_merge($result, $query);
print_r($result);
But you can work around like below.
Give loops and store in a third array from both the arrays and do necessary actions on third array.