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)
Related
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
}
}
I've received and XML, converted it into an array for usage.
The XML comes in unpredictable multi dimension when I convert it into array.
Had been looking around but could not find a suitable solution.
An alternative is to simplify the converted array.
I've converted an XML to array in PHP, and the result looked like this:
Array
(
[GetMLCBRes] => Array
(
[0] => Array
(
[Ord] => Array
(
[0] => Array
(
[OrdId] => Array
(
[0] => DP Order ID
)
)
)
[ReqInf] => Array
(
[0] => Array
(
[ReqDat] => Array
(
[0] => Date of Request
)
)
)
[Res] => Array
(
[0] => PDF Report
)
)
)
)
May I know how to drop the index like [0] but remain the assoc keys like [Ord], [OrdId], [ReqInf] and [Res], etc.
How to convert it to become like this?
Array
(
[GetMLCBRes] => Array
(
[Ord] => Array
(
[OrdId] => DP Order ID
)
[ReqInf] => Array
(
[ReqDat] => Date of Request
)
[Res] => PDF Report
)
)
it works but if you change your structure maybe it won't. It's not optimized too :)
$input = Array(
'GetMLCBRes' => Array(Array(
'Ord' => Array(Array(
'OrdId' => Array('DP Order ID')
)),
'ReqInf' => Array(Array(
'ReqDat' => Array('Date of Request')
)),
'Res' => Array('PDF Report')
))
);
foreach($input as &$in){
$sub = $in[0];
foreach($sub as $key => &$value){
$sub2 = $value[0];
if(!is_array($sub2)){
$sub[$key] = $sub2;
continue;
}
$final2 = array();
foreach($sub2 as $key2 => $final)
$final2[$key2] = $final[0];
$sub[$key] = $final2;
}
$in = $sub;
}
var_dump($input);
You can test it here : http://sandbox.onlinephpfunctions.com/code/a6770c7649d7d277aa1dc3544093cc87bed0951d
This should work as expected :
function recursive_skip(array $ary) {
foreach($ary as $k => &$v) {
if (is_array($v)) {
// Skip it
$v = $v[0];
}
if (is_array($v)) {
// If current array item is an array itself, recursively call the function on it
$v = recursive_skip($v);
}
}
// Return updated array to calling context
return $ary;
}
$source = Array(
'GetMLCBRes' => Array(Array(
'Ord' => Array(Array(
'OrdId' => Array('DP Order ID')
)),
'ReqInf' => Array(Array(
'ReqDat' => Array('Date of Request')
)),
'Res' => Array('PDF Report')
))
);
$dest = recursive_skip($source);
var_dump($dest);
A few caveats : the function will only skip one array level each time (but could be adapted to handle more if needed) and might come with a significant performance cost if your source array is huge since it's recursive (O(n)), it just walks through the whole array tree.
I'm newbie of codeigniter and PHP.
Can I separate an array into two different arrays?
This is my $array:
Array (
[0] => Array
(
[Name] => mark
[Surname] => mark
)[1] => Array
(
[Name] => greg
[Surname] => greg
)
)
Is it possible to create an array of $mark and another with $greg?
If you want to use the value of Name as your variable name: Variable variables
foreach ($arrays as $array) {
if (isset($array['Name'])) {
$$array['Name'] = $array;
}
}
print_r($mark);
You may use eval() if you want to set a string value and make it a variable.
<?php
$arrays = array(
array(
'Name' => 'mark',
'Surname' => 'mark'
),
array(
'Name' => 'greg',
'Surname' => 'greg'
)
);
//I'd use foreach()
foreach ($arrays as $array) {
eval("$".$array['Name']." = array('Name'=>'{$array['Name']}','Surname'=>'{$array['Surname']}',);");
}
echo '<pre>';
var_dump($mark, $greg);
echo '</pre>';
I have data that looks like this:
1 Root Catalog
1/2 Main Website
1/2/4 Cold Beverages
1/2/4/19 Pop - Canned
1/2/4/20 Pop - Natural Low Calorie
1/2/4/21 Pop - Bottled - Large Plastic
1/2/4/22 Pop - Bottled - Small Plastic
And need to turn it into an array that looks like:
array(
1 => array(
'name' => 'Root Catalog',
2 => array(
'name' => 'Main Website',
4 => array(
'name' => 'Cold Beverages',
19 => array(
'name' => 'Pop - Canned'
)
/*more numbers here*/
)
)
)
)
I can't figure out how to assign the array to the parent array while maintaining data integrity.
The issue I'm encountering is that I can have between 1-n levels nested. I've tried exploding the string and reconstructing it using recursion, but it never turns out right. Any idea's I could try?
edit: Best Attempt so far:
foreach ($categories as $category) {
$paths = explode('/', $category->getPath());
$paths = array_reverse($paths);
$temp = array('name' => $category->getName());
foreach ($paths as $key => $value) {
$temp = array($value => $temp);
}
$data = array_merge($data, $temp);
}
$data = array(
'1' => 'Root Catalog',
'1/2' => 'Main Website',
'1/2/4' => 'Cold Beverages',
'1/2/4/19' => 'Pop - Canned',
'1/2/4/20' => 'Pop - Natural Low Calorie',
'1/2/4/21' => 'Pop - Bottled - Large Plastic',
'1/2/4/22' => 'Pop - Bottled - Small Plastic'
);
$out = array();
foreach($data as $route => $value) // take every element of $data
{
$path = explode('/', $route); // split the route into elements
$current = &$out; // get pointer to the root of the output array
foreach($path as $level) // traverse through the path
{
if (!isset($current[$level])) // if branch does not exist, create it
$current[$level] = array();
$current = &$current[$level]; // set current pointer to that branch
}
$current['name'] = $value; // set leaf at the end of the branch
}
print_r($out); // output result
Result:
Array
(
[1] => Array
(
[name] => Root Catalog
[2] => Array
(
[name] => Main Website
[4] => Array
(
[name] => Cold Beverages
[19] => Array
(
[name] => Pop - Canned
)
[20] => Array
(
[name] => Pop - Natural Low Calorie
)
[21] => Array
(
[name] => Pop - Bottled - Large Plastic
)
[22] => Array
(
[name] => Pop - Bottled - Small Plastic
)
)
)
)
)
I've got an multi-array (currently with objects) that I want to reorder based on a specific key/value.
Array
(
[0] => stdClass Object
(
[task_id] => 1
[task_title] => Title
[users_username] => John
)
[1] => stdClass Object
(
[task_id] => 2
[task_title] => Title
[users_username] => John
)
[2] => stdClass Object
(
[task_id] => 3
[task_title] => Title
[users_username] => Mike
)
)
I'd like to reorder it to get multi-arrays by user_name, so I can cycle through the task by username.
Array
(
[John] => Array
(
[0] => Array
(
[task_id] => 1
[title] => Title
)
[1] => Array
(
[task_id] => 2
[title] => Title
)
)
[Mike] => Array
(
[0] => Array
(
[task_id] => 3
[title] => Title
)
)
)
Is it possible to recreate my array to an array like that above?
Updated version of the code
<?php
$it0 = (object) array('task_id' => 1,'task_title' => 'Title','users_username' => 'John');
$it1 = (object) array('task_id' => 2,'task_title' => 'Title','users_username' => 'John');
$it2 = (object) array('task_id' => 3,'task_title' => 'Title','users_username' => 'Mike');
$array = array($it0,$it1,$it2);
$return = array();
foreach($array as $id => $value){
$return[$value->users_username][] = array('task_id' => $value->task_id,'title' => $value->task_title);
}
var_dump($return);
Yes, it is possible.
You'll have to loop through your current array and create a new array to do it.
example:
$new_array = array();
foreach ($array as $row)
{
$new_row = array(
'task_id' => $row->task_id,
'title' => $row->task_title,
);
$name = $row->users_username;
if (isset($new_array[$name]))
{
$new_array[$name][] = $new_row;
}
else
{
$new_array[$name] = array($new_row);
}
}
Now $new_array contains the new array exactly like the one you're asking for.
Then you can sort it with
ksort($new_array);
There may be another way to do this, with some built-in function, but sometimes I'd rather just do it myself, and know how it is working, without having to look up the documentation.
The approach:
Iterate through all of the first array, looking at [users_username] and putting them into a new array.
Code:
$dst_array = array();
foreach ($src_array as $val)
{
$user = $val->users_username;
// TODO: This check may be unnecessary. Have to test to find out.
// If this username doesn't already have an array in the destination...
if (!array_key_exists($user, $dst_array))
$dst_array[$user] = array(); // Create a new array for that username
// Now add a new task_id and title entry in that username's array
$dst_array[$user][] = array(
'task_id' => $val->task_id
'title' => $val->title
);
}
Just something like this (maybe not 100% PHP code):
foreach ( $obj : $oldArray ) {
$newTask['task_id'] = $obj->task_id;
$newTask['title'] = $obj->title;
$newArray[$oldName][] = $newTask;
}
If you want to order it; you can just call a order function afterwards.