How do I loop through this array? - php

Well I'm relatively new to the use of PHP arrays and I have the follow array I need to loop through this array 2280 and 2307 are the identifiers.
I'm find it hard trying to come up with a foreach() that collects all the data.
Array
(
[2280] => Array
(
[0] => http://deals.com.au//uploads/deal_image/2706.jpg
[1] => Yuan's Massage and Beauty
[2] => Get Hair Free in CBD! Only $99 for SIX MONTHS worth of the latest in IPL Permanent Hair Reduction. Choose which area you want treated! Valued at $900 from Yuan's Massage and Beauty in the Heart of Melbourne's CBD. Limited vouchers available
[3] => 99
[4] => 900
[5] => 801
[6] => http://deals.com.au/1827
)
[2307] => Array
(
[0] => http://deals.com.au//uploads/deal_image/2683.jpg
[1] => Name Necklace Australia
[2] => Style yourself like SJP! Only $29 for a STERLING Silver Name Necklace plus get FREE delivery! Valued at $75 with NameNecklace.com.au
[3] => 29
[4] => 75
[5] => 46
[6] => http://deals.com.au/Melbourne
)
)

Your array snippet
$array = array( // foreach ($array as $k=>$subarray)
'2280' /* this is your $k */ =>
array( /* and this is your $subarray */
'http://deals.com.au//uploads/deal_image/2706.jpg',
And now you get data you need (you had to use nested foreach since values of your array are arrays):
foreach ($array as $k=>$subarray) {
foreach ($subarray as $data) {
echo $data;//of subarray
}
}
UPDATE
The OPs comment quistion on my answer:
what if I wanted to be selective rather than get a massive data dump.
if I echo $data how do I access specific rows?
Well, in most cases you should associate keys and data in your array (we call it associative array in PHP).
Example 1:
$hex_colors = array('FF0000', '00FF00' '0000FF');
Values are not assoiated with correspondent keys. PHP will assign 0,1,2... keys to arrays elements itself. In this case you would get green color's heximal value using auto-assigned by PHP 1 key: echo $hex_colors[1]; // 00FF00 and of course you should know it for sure. Usually this approach is used when you have strict data structure like array(red, green, bluee), but in most cases you better use the following approach:
Example 2:
$hex_colors = array('red'=>'FF0000', 'green'=>'00FF00' 'blue'=>'0000FF');
heximal colors representations are associated with appropriate keys echo $hex_colors['green']; // 00FF00
If your array was:
$array = array(
'2280' => array(
'image_url' => 'http://deals.com.au//uploads/deal_image/2706.jpg',
'product_name' => 'Yuan\'s Massage and Beauty',
'description' => 'Get Hair Free in CBD! Only $99 for SIX MONTHS worth of the latest in IPL Permanent Hair Reduction. Choose which area you want treated! Valued at $900 from Yuan's Massage and Beauty in the Heart of Melbourne's CBD. Limited vouchers available',
'price' => 99,
'weight_brutto' => 900,
'weight_netto' => 801,
'dealer_store' => 'http://deals.com.au/1827',
...
You would be able to access data using, let's call it "human-readable" keys:
foreach ($array as $id=>$product) {
echo 'Buy '.$product['name'].'';
echo '<img class="product_thumbnail" src="'.$product['image_url'].'" />';
echo 'Description: '.$product['description'];
echo 'The price is '.number_format($product['price']);
...
}
It is well-suited for reading rows from database, for example:
while ($data = mysql_fetch_array($query_result_link, MYSQL_ASSOC)) {
// MYSQL_ASSOC flag is not necessary
// PHP will use this flag by default for mysql_fetch_array function
// keys of $data will be correspondent columns names returned by mysql query
echo $data['id'];
echo $data['title'];
...
}
Continue learning PHP and you will find many more situations when it's more convenient to associate keys and values.

foreach ($arr1 as $key1 => $value1) {
//$key1==2280; $value1 is the array
foreach ($value1 as $key2 => $value2) {
//$key2==0;$value2="http://deals.com.au//uploads/deal_image/2706.jpg"
}
}

Related

Storing array data while using foreach

I have the following data here.
[places] => Array
(
[0] => Drama
[1] => School
[2] => Shounen Ai
[3] => Slice of Life
)
I am trying to store this data into WordPress tags, however it's returning only singular letters.
$i = 0;
foreach($t['places'] as $tag=>$value){
$numbers = $i++;
wp_set_object_terms($post_id , $t['places'][$numbers], "drama_tag",true);
}
This is what it returns, what am I doing wrong?
please edit the image into the post
You're looping over the array in your foreach; you don't need to set up your own increment.
Instead of $t['places'][$numbers], you're simply looking for $value:
foreach($t['places'] as $tag=>$value) {
wp_set_object_terms($post_id, $value, "drama_tag", true);
}

Remove records from multidimensional array

I am trying to remove records from a multidimensional array if certain criteria are met. The condition is that the element 'cap' should only have 'Capped' or Uncapped', if 'Other' is there, it should be removed from the array.
I have tried using Unset() but with no luck. It does not break the code, but it changes nothing. Output of the array:
[0] => Array
(
[name] => Club Name
[speed] => Annual Membership
[cap] => Other
[s_description] => Short description
[l_description] => Long description
)
[1] => Array
(
[name] => 50\5Mbps Fibre with 250GB
[speed] => Residential 50/5 Capped
[cap] => Capped
[s_description] => Short description
[l_description] => Long description
)
[2] => Array
(
[name] => FB-FP-B-V-50/5MBPS-400-24
[speed] => Residential 50/5 Capped
[cap] => Capped
[s_description] => Short description
[l_description] => Long description
)
Code for removing the 'Other' record:
foreach ($product_details['cap'] as $key ->$val_test) {
if ($val_test == "Other") {
unset($product_details[$key]);
}
}
I realise I may be doing something really stupid, but for something that should be fairly simple, it seems really difficult!
Thanks
Assuming your main array is stored under the variable: $product_details
Your code would be
foreach($product_details as $key => $product){
if($product['cap'] == "Other"){
unset($product_details[$key]);
}
}
You cant loop over '$product_details['cap']' as that is part of your inner array.
You must loop over your outer array then check the value of the inner array.
I hope this makes sense.
EDIT: On rereading of your question you could change your if statement to this to make it more open ended;
if($product['cap'] != "Capped" && $product['cap'] != "Uncapped"){
My solution
foreach ($your_array as $element) {
if ($element['cap'] == "Other") {
continue;
} else {
$newarray[] = $element;
}
}
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
Else you have to loop like above. There are other methods to map as well.

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

find out specific keys from arrray?

i have an array like this
[multiple_name] => Array
(
[0] => Change the business unit\'s root business unit
[1] => Change the business unit\'s parent business unit
[2] => Copy the business unit to the new position in the organizational hierarchy.
[3] => Disable the business unit, change the business unit s organization team and then activate the business unit
)
[multiple_correct] => Array
(
[1] => yes
)
now i want to print only key/index values from this array like '0,1,2,3' and from next one '1'.
kindly help me through this.. thanx in advance !!
Use foreach and bind the keys to a variable:
foreach($someArray as $key => $value) {
echo $key;
}
Where I supposed (from your question) that multiple_name and multiple_correct are not nested arrays, if they are though you need to foreach twice:
foreach($containerArray as $innerArray) {
foreach($innerArray as $key => $value) {
echo $key;
}
}

Optimize reordering and duplicate removal of multi-dimensional array

I wondering whether anyone has any good ideas on optimizing the following code. I have an multi-dimensional array ($List) as follows:
Array
(
[0] => Array
(
[id] => 1
[title] => A good read
[priority] => 10
)
[1] => Array
(
[id] => 2
[title] => A bad read
[priority] => 20
)
[2] => Array
(
[id] => 3
[title] => A good read
[priority] => 10
)
)
First I'm removing any entries that share the same title (no matter what the other values are) as follows:
$List_new = array();
foreach ($List as $val) {
$List_new[$val['title']] = $val;
}
$List = array_values($List_new);
Perfect. Then I'm reordering the array, first by the priority field and then id:
$sort_id = array();
$sort_priority = array();
foreach ($List as $key => $row) {
$sort_id[$key] = $row['id'];
$sort_priority[$key] = $row['priority'];
}
array_multisort($sort_priority, SORT_DESC, $sort_id, SORT_DESC, $List);
Both code blocks appear in a loop, hence the clearing of $sort_id and $sort_priority before reordering.
Is there a better way to do this - i.e. use the sorting process to remove duplicate title entries? This code block is being executed in a loop of up to 500,000 records and so any improvement would be welcome!
One loop, but a few extra function calls so I can't tell you how the Big O changes. One thing to note, the padding around numbers must be big enough to prevent overflow i.e. 2 = max 99 priorities and 6 = max 999,999 items.
$list_titles = array();
foreach($List as $val) {
if(isset($list_titles[$val['title']])) continue;
$list_titles[$val['title']] = true;
$List_new[str_pad($val['priority'], 2, 0, STR_PAD_LEFT).str_pad($val['id'], 6, 0, STR_PAD_LEFT)] = $val;
}
krsort($List_new);
Edit: made some minor modifications.

Categories