Return data from nested array - php

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 />' ;
}

Related

How can i foreach this array result and echo in codeigniter view

foreach this array result and echo the results
Array
(
[0] => Array
(
[0] => Array
(
[blog_title] => sooraj bloging
[blog_id] => 2
)
[1] => Array
(
[blog_title] => What are Mobile App Testing Challenges?
[blog_id] => 4
)
[2] => Array
(
[blog_title] => sooraj blog
[blog_id] => 8
)
)
[1] => Array
(
[0] => Array
(
[title] => sooraj casestudy
)
)
[2] => Array
(
[0] => Array
(
[career_id] => 14
[title] => Software Engineer .NET sooraj
[location] => Kochi, India.
[description] => Developing .NET applications.
[qualification] => B.Tech. in CSE, MCA
[status] => 0
[created_at] => 2017-11-20 13:14:29
[updated_at] => 0000-00-00 00:00:00
)
)
[3] => Array
(
)
[4] => Array
(
[0] => Array
(
[tst_id] => 146
[tst_name] => John Kasha
[tst_quote] => Gadgeon was extremely professional and was easy to commun sooraj icate and work with on a day-to-day basis. I also liked the fact that they were willing to do the research for specific tasks and present a viable solution or workaround to keep the project on schedule. I would recommend them for any task for any industry software or hardware. Bottom line, they get it done and you get results, not excuses. VP of Engineering.
[tst_desig] => Vice President,Product Development and Engineering
[tst_image] => 91c09ac9ee6234fdfcc523a393800bd5.jpg
[url] =>
[crop_name] => 668959f965ab28815dc97bbc1f8718d8.jpg
[sysDate] => 2017-11-20 15:42:34
)
)
)
Just Run this code
<?php
$array = array(
array(
array(
'blog_title' => 'sooraj bloging',
'blog_id' => 2
),
array(
'blog_title' => 'What are Mobile App Testing Challenges?',
'blog_id' => 4
),
array(
'blog_title' => 'sooraj blog',
'blog_id' => 8
)
),
array(
array(
'title' => 'sooraj casestudy',
)
),
array(
array(
'career_id' => 14,
'title' => 'Software Engineer .NET sooraj',
'location' => 'Kochi, India.',
'description' => 'Developing .NET applications.',
'qualification' => 'B.Tech. in CSE, MCA',
'status' => 0,
'created_at' => '2017-11-20 13:14:29',
'updated_at' => '0000-00-00 00:00:00'
)
),
array(),
array(
array(
'tst_id' => 146,
'tst_name' => 'John Kasha',
'tst_quote' => 'Gadgeon was extremely professional and was easy to commun sooraj icate and work with on a day-to-day basis. I also liked the fact that they were willing to do the research for specific tasks and present a viable solution or workaround to keep the project on schedule. I would recommend them for any task for any industry software or hardware. Bottom line, they get it done and you get results, not excuses. VP of Engineering.',
'tst_desig' => 'Vice President,Product Development and Engineering',
'tst_image' => '91c09ac9ee6234fdfcc523a393800bd5.jpg',
'url' => '',
'crop_name' => '668959f965ab28815dc97bbc1f8718d8.jpg',
'sysDate' => '2017-11-20 15:42:34'
)
)
);
foreach ($array as $value){
foreach ($value as $row){
foreach ($row as $key=> $row1){
echo $key.' - '. $row1;
}
echo '<br>';
}
}
?>
Depending what you're trying to do (debugging vs tabular display), you can "pretty print" the array with var_export like so:
// Assuming your array is $data
echo '<pre>'.var_export($data, TRUE).'</pre>';
Otherwise, to loop through the array as is with a foreach:
// Assuming your array is $data
foreach ($data as $subdata) {
// You probably want to check that this is an array for case #3
if(is_array($subdata)) {
foreach ($subdata as $valueset) {
// Check for array validity (not required for example data, but good to be safe)
if (is_array($valueset)) {
foreach ($subdata as $key => $value) {
// Print each key, value pair as a row
echo $key .' => '.$value . '<br />';
}
}
}
} else {
// Optional handling of empty set
echo 'No data to display...';
}
}
foreach ($array as $value){
foreach ($value as $row){
if (is_array($row)){
foreach ($row as $key => $val){
echo $key."=>". $val."<br>";
}///endForeach
}///endIf
else {
echo $row;
}////endElse
}
}

Removing associative array elements in numerical array and cleaning up the array duplicates

I am trying to resolve how to clean up my array and my output should be:
1) all numerical indexed and
2) no duplicate values.
This is a sampling of my current array output:
NOTE: index [3]. I am parsing those values into a new array and do not need either of them. They are merged onto the array below as you can see.
Ultimately I am preparing this for .csv format, but I need my array in some type of sequence in order to keep the data in proper presentation form.
Array // print_r();
(
[0] => 3350
[id] => 3350
[1] => Williamson New England Electric
[company] => Williamson New England Electric
[2] => bob#jojozzz.go
[email] => bob#jojozzz.go
[3] => Pumps & Motors,Electronic Systems,Electrical Supply,Electrical
[industry] => Pumps & Motors,Electronic Systems,Electrical Supply,Electrical
[4] => Pumps & Motors
[5] => Electronic Systems
[6] => Electrical Supply
[7] => Electrical
)
This is what I am trying to achieve:
Array
(
[0] => 3350
[1] => Williamson New England Electric
[2] => bob#jojozzz.go
[4] => Pumps & Motors
[5] => Electronic Systems
[6] => Electrical Supply
[7] => Electrical
)
As I said in my comment, it's probably easier to get the array as numerical array from the beginning, if you get it from a MySQL database:
$row = mysql_fetch_row($result);
Then you can do the following to split the value of the last column:
array_splice($row, -1, 1, explode(',', end($row)));
DEMO
See Felix's comment for a possible way to get your array in the right format at source. If thats not possible, this will do the trick;
$array = Array(
'0' => 3350,
'id' => 3350,
'1' => 'Williamson New England Electric',
'company' => 'Williamson New England Electric',
'2' => 'bob#jojozzz.go',
'email' => 'bob#jojozzz.go',
'3' => 'Pumps & Motors,Electronic Systems,Electrical Supply,Electrical ',
'industry' => 'Pumps & Motors,Electronic Systems,Electrical Supply,Electrical ',
'4' => 'Pumps & Motors',
'5' => 'Electronic Systems',
'6' => 'Electrical Supply',
'7' => 'Electrical'
);
$outputArray = array_values( $array );
$uniqueArray = array_unique( $outputArray );
var_dump( $uniqueArray );
Cannot guarantee anything about performance, but you can use is_numeric to ensure (#1) only numerical indexes, and use array_unique to ensure (#2) no duplicates:
$b = filterNonNumericKeysInArray($a);
$b = array_unique($b);
function filterNonNumericKeysInArray($arr) {
$finalArr = Array();
foreach ($arr as $key => $val) {
if (!is_numeric($key)) { continue; }
$finalArr[$key] = $val;
}
return $finalArr;
}

Breaking up array WHILE

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
}

how to slip this multi-dimensional array?

I have a nested array and I wanted to know if there is a way to slip it, so having the nested arrays as individual arrays
Array
(
[0] => Array
(
[menu] => Array
(
[pizza] => Array
(
[Tomato & Cheese] => Array
(
[small] => 5.50
[large] => 9.75
)
[Olives] => Array
(
[small] => 6.85
[large] => 10.85
)
)
[Speciality Pizzas] => Array
(
[Our Special] => Array
(
[ingredients] => Array
(
[0] => Tomatoes
[1] => Olives
[2] => Spinach
[3] => Fresh Garlic
[4] => Mozzarella & Feta Cheese
) --- theres more but you get the idea
Now I want to may a new array with all the pizzas, but without knowing the name "pizza"
at the moment I can do this:
$array = array(json_decode($json, true));
$pizzas = (array)$array[0]['menu']['pizza']
But if the menu changes content (but not structure) and if the 'pizza' changes to 'salads' the above would fail. Is the a way to create the above pizzas array without the name
Thanks
$array = array(json_decode($json, true));
$menu = (array)$array[0]['menu'];
foreach($menu as $item => $item_Data){
//$item might be pizza for example
//$item_Data might be Olives or Our special. Now you have to consider what to do with this. Maybe next foreach loop ?
}
Right now your array has parallel sections for related data. How about if you did something like:
$food_choices = array(
'pizza' => array(
'Tomato & Cheese' => array(
'type' => 'regular',
'prices' => array(...),
'ingredients' => array(...)
),
'Our Special' => array(
'type' => 'specialty',
'prices' => array(...),
'ingredients' => array(...)
),
),
'salads' => array(
'Caesar' => array(...);
'Tossed' => array(...);
)
)
where all the information related to any one menu item as all in the same branch of the meu tree. Then to access any one pizza's information is as simple as:
$data = $food_choices['pizza']['Tomato & Cheese'];
echo 'The large of this pizza costs $', $data['prices']['large'];
echo 'The small Caesar salad contains ', implode($food_choices['salad']['Caesar']['ingredients);
A series of foreach loops might do, even though I don't know what you're doing.
<?php
$pizza = '';
foreach ($array as $food) {
$pizza .= $food;
if (is_array($food)) {
foreach ($food as $option) {
$pizza .= " > " . $option;
if (is_array($option)) {
foreach ($option as $value) {
//etc
}
}
}
}
}
?>
To learn about the keys in an array, use the array_keys function (Demo):
$array = array(array('menu' => array(/* ... */))); # your array
print_r(array_keys($array[0])); # Array(menu)

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