I am working with an multidimensional array which I am receiving from a third party source so can not change the layout of it. Its for a collge and I want to loop the module names but not the ID's.
When using this foreachloop
<?php echo "<ul>";
foreach($array['Course']['Modules']['Module'] as $key => $value)
{
foreach($value as $keys => $values)
{
echo "<li>";
foreach($values as $thirdkey => $thirdvalues)
{
echo $thirdvalues . " " ;
}
echo "</li>";
}
}
echo "</ul>"
?>
I get the following which is fine but I don't need the moduleID:
003646 T.I.G. WELDING ALUMINIMUM INTERMEDIATE
003644 T.I.G. WELDING STAINLESS STEEL INTERMEDIATE
003633 MIG WELDING INTERMEDIATE
003552 MANUAL METAL ARC WELDING INTERMEDIATE
000016 MOUNTING OF ABRASIVE WHEELS
003299 MACHINE TOOLS (WELDING)
000001 INDUCTION
000002 CAREER PLANNING AND JOB SEEKING SKILLS
000029 OXY-ACETYLENE CUTTING
003757 THEORY OF WELDING
000003 IN-COMPANY
000664 SAFEPASS
This is my array, can anyone help me return just the Module Title???
Array
([Certification] => IT Systems Support - PC Maintenance (L1)
[Modules] => Array
(
[Module] => Array
(
[0] => Array
(
[#attributes] => Array
(
[ModuleID] => 004839
[Title] => IT SYSTEMS SUPPORT- PC MAINTENANCE
)
)
[1] => Array
(
[#attributes] => Array
(
[ModuleID] => 007685
[Title] => COMPTIA A+ - 220 801
)
)
[2] => Array
(
[#attributes] => Array
(
[ModuleID] => 007684
[Title] => COMPTIA A+ - 220-802
)
)
[3] => Array
(
[#attributes] => Array
(
[ModuleID] => 004757
[Title] => PREPARING FOR WORK
)
)
)
)
)
Thank in advance :)
You could just directly point to it.
foreach($array['Course']['Modules']['Module'] as $key => $value) {
echo "<li>{$value['#attributes']['Title']}</li>";
}
Sidenote: Most likely this is a SimpleXML object, fed into a json encode/decode.
$array = json_decode(json_encode($xml), true); // actually don't need to do this one
I'd suggest just use SimpleXML all through out as it is already capable of getting all those values.
You didn't care to try $thirdvalues["Title"] right?, looks like a mess but I don't see why it wouldn't work if you got it to print that.
can also do if( $key == "Title" ) echo $value
Related
I have a query that I'm running and it will output an unknown number of results. I want to display these results in a table of 5 columns. So I need the array print until the sixth result and then start a new row.
The way I tried to do it was to take the original array and chunk it into blocks of 5.
$display=array_chunk($row_Classrooms,5);
which gives me an array like this.
Array (
[0] => Array (
[0] => Array (
[id_room] => 1
[Name] => Classroom 1
[class] => Yes
)
[1] => Array (
[id_room] => 5
[Name] => Classroom 2
[class] => Yes
)
[2] => Array (
[id_room] => 6
[Name] => Classroom 3
[class] => Yes
)
[3] => Array (
[id_room] => 7
[Name] => Classroom 4
[class] => Yes
)
[4] => Array (
[id_room] => 8
[Name] => Classroom 5
[class] => Yes
)
)
[1] => Array (
[0] => Array (
[id_room] => 9
[Name] => Classroom 6
[class] => Yes
)
)
)
I'm then trying to echo this out with a pair of while loops, like such.
while ($rows = $display) {
echo '<tr>';
while ($class = $rows) {
echo'<td>'.$class['name'].'<br>
<input name="check'.$i.' type="checkbox" value="'.$class['id_room'].'></td>';
$i++;
}
echo '</tr>';
}
When I run this it apparently gets stuck in a never ending loop because nothing gets displayed but the browser just keeps chewing up more and more memory :)
The while statements are wrong. Have a look at here - in your while-statement you are always assigning the complete $display - not one entry.
You could try using while(($rows = array_shift($display)) !== false) - that will always get the first array item until there are no more items.
The same case in the second while-statement.
I ended up replacing the while loops with foreach loops instead which solved the issue.
foreach ($display as $rows) {
echo '<tr class="popup">';
foreach($rows as $class) {
if(isset($row_Rego)){
$exist=NULL;
$exist=array_search($class['id_room'], array_column($row_Rego, 'id_room'));
}
I'm having a real headache trying to iterate through an array and output elements. Using the array structure below I want to be able to output each instance of partname.
The following loop outputs the first instance of partname. I can't seem to adapt it to loop through all instances within the array. I'm sure I'm missing something basic.
foreach($ItemsArray['assignments'] as $item) {
$partname = $item['grades'][0]['partname'];
}
Array
(
[assignments] => Array
(
[0] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6601
[partname] => Draft
[userid] => 82069
[grade] => 53
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
[1] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6602
[partname] => Final
[userid] => 82069
[grade] => 35
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
)
)
Instead of just coding by slapping the keyboard. Write down what your function needs to do. In english (or whatever language you prefer). This would be something like:
Foreach assignment, loop over all grades and store the partname of
that grade into an array.
And then code it:
function getPartnames($assignments) {
$partNames = array();
foreach ($assignments as $assignment) {
foreach($assignment['grades'] as $grade) {
$partNames[] = $grade['partname'];
}
}
return $partNames;
}
So what did I do? I simply translated english to code.
Some few more tips: Use variables names that make sense. $item; $ItemArray; ... don't make sense. They tell me nothing
use an extra foreach in your loop:
foreach($ItemsArray['assignments'] as $item) {
foreach($item['grades'] as $grade) {
echo $grade['partname'];
}
}
here is my code
array 1:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
)
)
array 2:
Array
(
[0] => Array
(
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
[company_id] => 42166
)
)
php code:
$total = count($result);
$i=0;
foreach ($result as $key=>$value) {
$i++;
$company_id= implode(",",(array)$value['id']);
if ($i != $total)
echo',';
}
code to fetch array 2:
foreach ($res as $key1=>$value1) {
echo $total;
$event[$value['company_name']] = $value1['Product_Name'];
if($value1['company_id']==$company_id )
{
echo " match";
//$key[['company_name']]= $value1['Product_Name'];
}
else
{
echo "not matched";
}
}
what i need create a new index if company_id is match with id of another array.
that is product_name.
if product name is there just create index otherwise show null.
i want show in key=> value .
output should be like:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
)
)
Your all problems with keys in arrays will disappear when you will start using company ids as a keys.
To reindex you arrays, you can use:
$array1 = array_combine(array_column($array1, 'id'), $array1);
$array2 = array_combine(array_column($array2, 'company_id'), $array2);
In the output you will get:
array 1:
Array
(
[42166] => Array
(
[id] => 42166
...
)
)
And array 2 will looks similiar - id as a key.
So accessing to the elements using ids as a keys is a piece of cake right now.
So I am print_r-ing an array, generated as follows:
while ($twitgroup = mysql_fetch_array($resulttwitter)) {
print_r($twitgroup);
}
I get this output (with multiple more arrays, dependent on rows).
Array ( [0] => composed [category] => composed [1] => 330 [value] => 330 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => elated [category] => elated [1] => 2034 [value] => 2034 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => unsure [category] => unsure [1] => 2868 [value] => 2868 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => clearheaded [category] => clearheaded [1] => 1008 [value] => 1008 [2] => 1344384476.94 [timestamp] => 1344384476.94 ) Array ( [0] => tired [category] => tired [1] => 2022 [value] => 2022 [2] => 1344384476.94 [timestamp] => 1344384476.94 )
I want to be able to pull individual values here, but I'm having trouble. I'm trying to use a while loop on these arrays, but I think maybe that's wrong. Should I perhaps use a foreach loop, and then on the output of that foreach, access each element of the array?
Say for example, I want to grab composed, and the value of composed. How would I do that?
I'm pretty good with arrays/lists in Python, but my experience with arrays in PHP is somewhat lacking.
Use
while ($row = mysql_fetch_assoc($resulttwitter)) {
$twitgroup[$row['category']] = $row;
}
echo $twitgroup['composed']['value']; // outputs 330
echo $twitgroup['composed']['timestamp']; // outputs 1344384476.94
If you only want categories and their values use
while ($row = mysql_fetch_assoc($resulttwitter)) {
$twitgroup[$row['category']] = $row['value'];
}
echo $twitgroup['composed']; // outputs 330
Replace mysql_fetch_array with mysql_fetch_assoc to eliminate duplicates. Then this:
while ($twitgroup = mysql_fetch_assoc($resulttwitter))
{
foreach ($twitgroup as $key => $value)
{
echo "$key => $value\n";
}
}
You could also get the elements by name:
while ($twitgroup = mysql_fetch_assoc($resulttwitter))
{
echo "category => " . $twitgroup["category"] . "\n";
echo "value => " . $twitgroup["value"] . "\n";
echo "timestamp => " . $twitgroup["timestamp"] . "\n";
}
mysql_fetch_array includes each field twice in the result, one associated with a numeric key and one with the field name.
That is why you have
[0] => composed
[category] => composed
[1] => 330
[value] => 330
You can access field either like :
$twitgroup[0]
or like :
$twitgroup['category']
So, you can access your each row like :
while ($twitgroup = mysql_fetch_array($resulttwitter)) {
print $twitgroup['category']; // or print $twitgroup['0'];
print $twitgroup['value']; // // or print $twitgroup['1'];
// or by the corresponding numeric indices.
}
If at all you want to limit your result to either numeric or Associative array, add an additional flag (result_type) to your mysql_fetch_array :
mysql_fetch_array ($resulttwitter, MYSQL_ASSOC) // or mysql_fetch_array ($resulttwitter, MYSQL_NUM)
Having said all this, it is highly discouraged using mysql_* functions in PHP since they are deprecated. You should use either mysqli or PDO instead.
This is what you have:
Array (
[0] => composed
[category] => composed
[1] => 330
[value] => 330
[2] => 1344384476.94
[timestamp] => 1344384476.94
) Array (
[] =>
[] =>
...
) ...
Arrays in PHP are called associative arrays because they can have
either keys out of integers, strings or anything else.
You have an array with arrays in it.
To access the individual fields, it would be most convenient to use a
for each loop.
$record=0;
foreach ($array as $k => $subArray) {
$record++;
foreach($subArray as $field => $value) {
printf("%d: %s = %s\n", $record, $field, $value);
}
}
Its seems to me that there is something wrong with the way you are fetching
the data, becasue half the fields seem redundant. You can use the string keys
to figure out the contents. so there is no need for the n => name entries.
If that can't be helped, I guess you could iterate over the values with
$ix=0;
for ($i=0; $i < (count($array)/2); $i++){
printf("%s\n", $array[$ix]);
$ix++;
}
Edit: Thanks to #Felix Kling and #mario for pointing me towards named capture groups and PREG_SET_ORDER, I totally learned something today.
I'm curious about a better algorithm per se, though. So please just pretend that there's no preg_match() involved.
Edit 2: Abstracted question
While answering another question here, I stumbled upon the fact that my code for turning
this:
Array
(
[0] => Array (
[0] => 1
[1] => 3
)
[1] => Array (
[0] => Description text
[1] => Different Description text
)
[2] => Array (
[0] => 123.456.12
[1] => 234.567.89
)
[3] => Array (
[0] => 10.00
[1] => 10.00
)
[4] => Array (
[0] => 10.00
[1] => 30.00
)
)
into that:
Array
(
[0] => Array
(
[qty] => 1
[description] => "Description text"
[sku] => 123.456.12
[price] => 10.00
[total] => 10.00
)
…
)
is fugly:
$field_names = array('qty', 'description', 'sku', 'price', 'total');
$result_arr = array();
$num_iter = count(matches[0]);
for ($i = 0; $i < $num_iter; $i++) {
foreach ($field_names as $index => $field_name) {
$result_arr[$i][$field_name] = array_shift($input_arr[$index]);
}
}
Any suggestions for improvement?
There is one simpler way to produce the desired output.
while (count($input_arr[0])) {
$values = array_map("array_shift", & $input_arr);
$result_arr[] = array_combine($field_names, $values);
}
This won't work past PHP 5.3, as it requires forcibly passing a parameter by reference. (Avoiding any dumbing-down-the-language remarks here). But you can of course chop off the entries with a more elaborate manual loop at any time.
The real simplification for such cases is however array_combine to turn a list into an associative array.