Breaking up array WHILE - php

I'm implementing memcached on a site and I'm caching the results of a specific query, which is working great, but I am having problems putting together the code to set the variables I need to make the cache usable.
My array is as follows, which contains two groups of data:
Array ( [0] => Array ( [0] => 9126 [id] => 9126 [1] => Oh penguin, you so silly. [title] => Oh penguin, you so silly. [2] => November-01-2011-00-14-09-ScreenShot20111031at9.jpg [path] => November-01-2011-00-14-09-ScreenShot20111031at9.jpg ) [1] => Array ( [0] => 9131 [id] => 9131 [1] => Reasons you die... [title] => Reasons you die... [2] => November-01-2011-00-17-04-ScreenShot20111031at8.jpg [path] => November-01-2011-00-17-04-ScreenShot20111031at8.jpg ) )
I can set them manually, and call them like this:
$id = $clean[0][0];
$title = $clean[0][1];
$path = $clean[0][2];
But I am having problems writing a WHILE loop to go through and set the variables dynamically. I also tried a FOR EACH statement to no avail:
for each($clean as $image){
$id = $image->id;
$path = $image->path;
$title = $image->title;
echo "THIS IS YOUR FREAKING ID $id THIS IS YOUR TITLE $title THIS IS YOUR PATH $path";
}
Any insight?
Edit:
Solution was to not call them as objects, as pointed out, change to reference them like this:
$id = $image["id"];
$path = $image["path"];
$title = $image["title"];
Cheers.

$array = array(
array ( 0 => 9126,
'id' => 9126,
1 => 'Oh penguin, you so silly.',
'title' => 'Oh penguin, you so silly.',
2 => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg',
'path' => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg' ),
array ( 0 => 9126,
'id' => 9126,
1 => 'Oh penguin, you so silly.',
'title' => 'Oh penguin, you so silly.',
2 => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg',
'path' => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg' )
);
foreach( $array as $row)
{
// Based on your array, you can either do:
echo $row['id'] . ' ' . $row['title'] . $row['path']. "\n";
echo $row[0] . ' ' . $row[1] . ' ' . $row[ 2 ] . "\n";
}

You could just serialize the entire array before saving in cache, then unserialize when you retrieve from cache. Then just reference the values as you indicated.

For each should serve you well. If you need to iterate through $clean as well just wrap around another foreach.
$arr = $clean[0];
foreach ($arr as $value) {
echo $value; // or in your case set
}

Related

Return data from nested array

I'm trying to get some data from Wikipedia API. I found this project https://github.com/donwilson/PHP-Wikipedia-Syntax-Parser but I cannot figure out how to output the infobox entries in a loop, because the array is in an array which is in an array.
The array code
[infoboxes] => Array
(
[0] => Array
(
[type] => musical artist
[type_key] => musical_artist
[contents] => Array
(
[0] => Array
(
[key] => name
[value] => George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>
)
[1] => Array
(
[key] => image
[value] => George Harrison 1974 edited.jpg
)
[2] => Array
(
[key] => alt
[value] => Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.
)
[3] => Array
(
[key] => caption
[value] => George Harrison at the White House in 1974.
)
)
)
)
This is what I tried (returns the value but not the key)
$values=$parsed_wiki_syntax["infoboxes"][0]["contents"];
$keys = array_keys($values);
for($i=0; $i<count($values); $i++){
foreach ($values[$keys[$i]] as $key=>$value)
echo "<b>".$key."</b>: ".$value."<br><br>";
}
Let's just see what happens when we simplify everything a little bit:
$firstBox = reset($parsed_wiki_syntax['infoboxes']);
if($firstBox) {
foreach($firstBox['contents'] as $content) {
$key = $content['key'];
$value = $content['value'];
echo "<b>" . $key . "</b>: " . $value . "<br><br>";
}
}
The use of array_keys() and the for/foreach loops get a little confusing quickly, so I'm not sure exactly what your error is without looking more. The big trick with my code above is the use of reset() which resets an array and returns (the first element). This lets us grab the first infobox and check if it exists in the next line (before attempting to get the contents of a non-existent key). Next, we just loop through all contents of this first infobox and access the key and value keys directly.
You if want to access both keys and values, a simple good ol' foreach will do. Consider this example:
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$contents = $values['infoboxes'][0]['contents'];
foreach($contents as $key => $value) {
echo "[key => " . $value['key'] . "][value = " . htmlentities($value['value']) . "]<br/>";
// just used htmlentities just as to not mess up the echo since there are html tags inside the value
}
Sample Output:
[key => name][value = George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>]
[key => image][value = George Harrison 1974 edited.jpg]
[key => alt][value = Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.]
[key => caption][value = George Harrison at the White House in 1974.]
Sample Fiddle
As an exercise in scanning the given array without hardcoding anything.
It doesn't simplify anything, it is not as clear as some of the other answers, however, it would process any structure like this whatever the keys were.
It uses the 'inherited' iterator, that all arrays have, for the 'types' and foreach for the contents.
<?php
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$typeList = current(current($values));
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), '...', '<br />';
foreach(current($typeList) as $content) {
$key = current($content);
next($content);
echo 'content: ', $key, ' => ', current($content), '<br />' ;
}

how to iterate through a particular part of an object

I have an object which looks like this
zen_categories_ul_generator Object
(
[root_category_id] => 0
[max_level] => 6
[data] => Array
(
[0] => Array
(
[19] => Array
(
[name] => Brushes
[count] => 0
)
[29] => Array
(
[name] => Clips
[count] => 0
)
[2] => Array
(
[name] => Combs
[count] => 0
)
[27] => Array
(
[name] => Jewellery
[count] => 0
)
)
[1] => Array
(
[57] => Array
(
[name] => Testing
[count] => 0
)
)
And I want to loop through all the information at the level $this->data[0], I'm using
foreach($this->data[0] as $category_id => $category) {
$result .= $category_id.' - '.$category['name'];
}
return $result;
but this will just the last item in the array. so in this case it would only have 27 - Jewellery but none of the other array item would be returned.
What am I doing wrong?
thanks
NB I only need to loop through the data[0] - not data[1] as well!
EDIT - here's a paste bin with a more code to make easier to understand what I'm trying to do and how I'm doing it. Any help gratefully received
http://pastebin.com/Vrw9f7Xh
Question:
Ok, so you want to loop through all the information $this->data[0], to render a menu.
Actually, you were pretty close to the solution, yourself.
The line used for rendering the product items, is:
$result .= ''.$category['name'] . ' (' . $category['count'] . ')';
The following is working example, which works standalone.
You might save it as menu.php and test it.
I had to comment the zen_* function out, but i think the relevant part is the rendering, right?
class zen_categories_ul_generator
{
function setTestData($data) { $this->data = $data; }
function buildMenu() {
$result = '';
// removed home link, unchanged and not important in this example
// submenu
$result .= '<li class="submenu">';
$result .= 'Products';
$count = 0;
foreach($this->data[0] as $category_id => $category) {
$count++;
$result .= '<ul class="level2">';
$result .= '<li class="submenu">';
//$result .= ''.$category['name'].''.$count;
$result .= ''.$category['name'] . ' (' . $category['count'] . ')';
$result .= '</li>';
$result .= '</ul>';
}
$result .= '</li> Items:' . $count;
return $result;
}
}
$object = new zen_categories_ul_generator;
// ok, lets add your example data from outside to the object, in order to test the rendering
$data = array(
0 => array(
19 => array('name' => 'Brushes', 'count' => 5),
29 => array('name' => 'Clips', 'count' => 2),
2 => array('name' => 'Combs', 'count' => 1),
27 => array('name' => 'Jewellery', 'count' => 3)
)
);
$object->setTestData($data);
// render the menu
echo $object->buildMenu();
Result
Count is the number of iterations = the number of Products in a Category.
And the counter behind the product name is from the array, the key "count".

How to print specified array value

I am fetch facebook user's working history, and when I print_r, I get an array like this:
Array (
[work] => Array (
[0] => Array (
[employer] => Array (
[id] => 111178415566505
[name] => Liputan 6 SCTV
)
) [1] => Array (
[employer] => Array (
[id] => 107900732566334
[name] => SCTV
)
)
)
[id] => 502163984
)
How do I display only the value from name, so the output will be like this:
Liputan 6 SCTV
SCTV
I used foreach, but always an error always happens.
Try this:
foreach ($array['work'] as $arr) {
echo $arr['employer']['name']."<br>\n";
}
This is assuming your data looks like:
$array = array(
'work' => array(
array(
'employer' => array('id' => 111178415566505, 'name' => 'Liputan 6 SCTV'),
),
array(
'employer' => array('id' => 107900732566334, 'name' => 'SCTV'),
),
),
'id' => 502163984,
);
for instance your array variable name is $test, then you can get name value by
$test['work'][0]['employer']['name']
you can check your array structure using pre tag, like
echo '<pre>';print_r($test);
You can use array_reduce, implode, and closure (PHP 5.3+) to do this.
echo implode("<br/>", array_reduce($array["work"],
function(&$arr, $v){
$arr[] = $v["employer"]["name"];
},array()
));
I assume $arr is working history array. You can use for Then array look like this :
for($i=0, $records = count( $arr['work']); $i < $records; $i++) {
echo $arr['work'][$i]['employer']['name'] ."<br>";
}
Using foreach
foreach( $arr['work'] as $works) {
echo $works['employer']['name'] ."<br>";
}
foreach ($your_array as $your_array_item)
{
echo $your_array_item['work'][0]['employer']['name'] . '<br>';
}
$count=count($array);
for($i=0,$i<=$count;$i++){
echo $array['work'][$i]['employer']['name'];
}
This will work.. Dynamically..
foreach ($array['work'] as $val_arr) {
echo $val_arr['employer']['name']."<br />";
}

PHP concatenation skips line on empty value

I'm trying to concatenate an array, but when PHP comes across an empty array-item, it stops concatenating.
My array looks like this:
Array
(
[0] => Array
(
[0] => Test1
[1] => Test1
[2] =>
)
[1] => Array
(
[0] => Test2
[1] => Test2
[2] =>
)
[2] => Array
(
[0] => Test3
[1] => Test3
[2] => Test3
)
)
The 3th item on the first 2 Array-items are empty. And when I loop over them like this:
$keys = array('uid', 'type', 'some_column', 'other_column');
foreach ($csv as $i => $row) {
$uid = $row[0] . $row[1] . $row[2];
array_unshift($row, $uid);
$csv[$i] = array_combine($keys, $row);
}
I only get Test3Test3Test3 back, instead of the expected
Test1Test1
Test2Test2
Test3Test3Test3
So it looks like PHP is skipping items when concatenating an empty value.
Is this normal PHP behavior? And if so, how can I tackle this?
Try like
$uid = array();
foreach ($array as $i => $row) {
$uid[] = $row[0] . $row[1] . $row[2];
}
var_dump($uid);
Just you are giving $uid and it is taking it as an type variable and it appends the last occurance of loop into that variable.If you want your desired output you need to declare it as an array before.
I'm sorry, but if that is your desired output, you're overcomplicating things:
$foo = array(
array("Test1","Test1"),
array("Test2","Test2"),
array("Test3","Test3","Test3")
);
echo implode(PHP_EOL,
//implode all child arrays, by mapping, passes no delimiter
//behaves as concatenation
array_map('implode',$foo)
);
Returns:
Test1Test1
Test2Test2
Test3Test3Test3
In your case, you can use bits of this code like so:
$csv = array(array("Test1","Test1",''),array("Test2","Test2",''),array("Test3","Test3","Test3"));
$keys = array('uid', 'type', 'some_column', 'other_column');
foreach($csv as $k => $row)
{
array_unshift($row,implode('',$row));
$csv[$k] = array_combine($keys,$row);
}
gives:
Array
(
[0] => Array
(
[uid] => Test1Test1
[type] => Test1
[some_column] => Test1
[other_column] =>
)
[1] => Array
(
[uid] => Test2Test2
[type] => Test2
[some_column] => Test2
[other_column] =>
)
[2] => Array
(
[uid] => Test3Test3Test3
[type] => Test3
[some_column] => Test3
[other_column] => Test3
)
)
Try this:
$uid = array();
foreach ($array as $i => $row) {
$uid[] = $row[0] . $row[1] . $row[2];
}
var_dump($uid);
This outputs:
Array
(
[0] => Test1Test1
[1] => Test2Test2
[2] => Test3Test3Test3
)
You can do something similar to produce a string:
$uid = '';
foreach ($arr as $i => $row) {
$uid .= $row[0] . $row[1] . $row[2] . "\n";
}
echo $uid;
Output:
Test1Test1
Test2Test2
Test3Test3Test3
To get the expected output
$uid = "";
foreach ($array as $i => $row) {
$uid .= $row[0] . $row[1] . $row[2] . "\n";
}
echo $uid;
You need to use two foreach loop..
Procedure:
Initialize your first foreach loop to get the key => value as $key=> $value of each array inside.
Then initialize your second loop to $value variable since value inside of this is another array key => value = $innerKey => $innerValue.
Then inside your second loop echo $innerValue to display values inside of the secondary array
Lastly put an echo '<br/>' inside your first loop to put each secondary array into another newline.`
.
$data = array(
0 => array(
0 => 'Test1',
1 => 'Test1',
2 => ''
),
1 => array(
0 => 'Test2',
1 => 'Test2',
2 => ''
),
2 => array(
0 => 'Test3',
1 => 'Test3',
2 => 'Test3'
)
);
foreach($data as $key => $value){
foreach($value as $innerKey => $innerValue){
echo $innerValue;
}
echo '<br/>';
}
// Output would be..
Test1Test1
Test2Test2
Test3Test3Test3
Code Tested at : PHP Fiddle

How to use keys and values in foreach using php?

I am having the following friendDetails array output,
Array
(
[0] => Array
(
[id] => 1
[first_name] => Aruun
[last_name] => Sukumar
[photo] => jpg
)
[1] => Array
(
[id] => 2
[first_name] => senthilkumar
[last_name] => Kumar
[photo] => jpg
)
)
I use the following piece of code to to get final output
foreach($friendDetails as $value){
array_push($friendList, $value[id].".".$value[photo]."-".$value[first_name]." ".$value[last_name]);
}
Final output will be,
Array
(
[0] => 1.jpg-Aruun Sukumar
[1] => 2.jpg-senthilkumar Kumar
[2] => 18.jpg-senthilkumar sugumar
)
Here I am getting Notice Error with exact output. What i done wrong on the code?
Is there any other way to get Final Output ?
You get the notice error as you are not putting the keys of your array in quotes.
It should be:
foreach($friendDetails as $value){
array_push($friendList, $value['id'].".".$value['photo']."-".$value['first_name']." ".$value['last_name']);
}
see http://php.net/manual/en/language.types.array.php
You need to put quotes around your key identifiers:
$value['id'] . "." . $value['photo']
etc. See "Why is $foo[bar] wrong?" at http://php.net/manual/en/language.types.array.php
Try this you will get both key and value:
foreach ($friendDetails as $key_name => $key_value) {
print "Key = " . $key_name . " Value = " . $key_value . "<BR>";
}
Two things:
You need to put quotes (") around the array keys in the array_push (i.e. $value["id"])
Make sure that you define $friendList as an array before the foreach.
A working example:
<?php
$friendDetails = array(
array(
'id' => 1,
'first_name' => 'Aruun',
'last_name' => 'Sukumar',
'photo' => 'jpg'
),
array(
'id' => 2,
'first_name' => 'senthilkumar',
'last_name' => 'Kumar',
'photo' => 'jpg'
)
);
$friendList = array();
foreach($friendDetails as $value){
array_push($friendList, $value["id"].".".$value["photo"]."-".$value["first_name"]." ".$value["last_name"]);
}
print_r($friendList);
?>
Use quotations around your array values:
foreach($friendDetails as $value){
array_push($friendList, $value['id'].".".$value['photo']."-".$value['first_name']." ".$value['last_name']);
}
$friendList = array();
foreach($friendDetails as $key=> $value){
$friendList[] = $value['id'].".".$value['photo']."-".$value['first_name']." ".$value['last_name']);
}

Categories