tree traversal to nth node - php

I have a multidimensional array.
$tree= [
"wood"=> [
"segun",
"koroi",
"karosin"
],
"food"=> [
'grain',
"vegetable"=> [
"potato",
"tomato"=>[
"small"=>["cherri","local"],
"big"=>["green","red"]
],
"radish"
],
"fruits"=> [
"mango"=>[
"lengra",
"amrupali",
"fozli",
"him sagar"
],
"jak fruits"
]
],
"medicine"=> [
"nim",
"arjun",
"amla"
],
"oxygen",
"computer"
];
I am using this code to show
function treeView($tree){
$markup='';
foreach ($tree as $key=>$value){
$markup.= '<li>'. (is_array($value) ? $key. treeView($value) : $value) .'</li>';
}
return "<ul>".$markup."</ul>";
}
I want to show upto 2 nodes of each element. This is not fixed, it can be nth nodes depends on user input. I am not getting it how to solve this.
If user input 3, I would like show the output like this
If user input 2, I would like show the output like this

Just add an optional "defaults to 0" level parameter.
function treeView($tree, $max_level = 2, $current_level = 0)
{
if ($max_level == $current_level) {
return "";
}
$markup = '';
foreach ($tree as $key => $value) {
$markup .= '<li>' . (is_array($value) ? $key . treeView($value, $max_level, $current_level + 1) : $value) . '</li>';
}
return "<ul>" . $markup . "</ul>";
}

Related

PHP list array and get value

I have some difficulties with PHP Arrays. I'm trying to foreach some values, order them with array_multisort and foreach them again so I can create some kind of code.
So what I'm doing is, I'm passing json object as:
"options": [
{"key": "Ships From", "value": "Russia"},
{"key": "Color", "value": "Green"},
{"key": "Size", "value": "M"},
{"key": "Material", "value": "Flex"}
],
So this is received from frontend, and I'm foreaching them like so:
public function findAttribute($product_id, $values)
{
$array = array();
foreach ($values as $key => $value) {
$getAttr = $this->attribute($value['key']);
$getAttrValue = $this->attributeValue($getAttr->id, $value['value']);
$code = $getAttr['label'] . '=' . $getAttrValue['value'];
$collection = array_push($array, array($getAttr->default_order, $code));
}
array_multisort($array, SORT_ASC);
}
As you can see I have $getAttr and $getAttrValue, that selects values from database, in order to get default_order (integer) so I can sort them with multisort.
So actually this code works as expected, and when I write (after multisort) like:
foreach($array as $key => $value){
echo $value[1] .'/';
}
I have expected value, but when I call that function it gives me that it returns NULL, if I change echo to return, I have only first array. If I try like
foreach($array as $key => $value){
$code = $value[1] .'/';
}
return $code;
No success as well.
What should I do?
Because in each iteration you assign a new value to $code so you will only get the last $value [1] in the array (after arranged).
If you want to return a string concatenating all values, you could do as this:
$code = '';
foreach($array as $key => $value){
$code .= $value[1] .'/';
}
return $code;
$code = array();
foreach($array as $key => $value){
$code = $value[$key] .'/';
}
return $code;
Implement your code i hope that will work.

Dynamically parse multiple json array objects with php

I have a json file as below name "brands.json"
{
"title":"List of brands",
"version" : 1,
"nike": [
{"type":"shoes","size":10,"color":"black"},
{"type":"shirt","size":"S","color":"black"}
],
"converse": [
{"type":"shoes","size":10,"color":"red"},
{"type":"backpack","size":"N/A","color":"red"}
],
"champion": [
{"type":"shoes","size":10,"color":"blue"},
{"type":"pants","size":"M","color":"grey"}
]
}
I looked at some example online and get this piece of code
<?php
$read = file_get_contents("report.json");
$json = json_decode($read, true);
foreach($json as $key => $val){
if(is_array($val)){
echo "$key : <br>";
foreach($key as $k => $v){
echo "$k => $v<br>";
}
}
else {
echo "$key => $val<br>";
}
}
?>
I would be able to print out
title => List of brands
version => 1
nike :
converse :
champion :
But I would like to get the array inside of those brands. I was thinking of having a foreach loop inside the if statement. However, it returns errors
nike : Warning: Invalid argument supplied for foreach().
Some resources suggested to do something like $json->nike as $item => $v but that will be redundant since I also have converse and champion arrays. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated.
Expected table
Nike:
type | size | color
shoes| 10 | black
shirt| S | black
Create function that buffers output and display it
$read = '{
"title":"List of brands",
"version" : 1,
"nike": [
{"type":"shoes","size":10,"color":"black"},
{"type":"shirt","size":"S","color":"black"}
],
"converse": [
{"type":"shoes","size":10,"color":"red"},
{"type":"backpack","size":"N/A","color":"red"}
],
"champion": [
{"type":"shoes","size":10,"color":"blue"},
{"type":"pants","size":"M","color":"grey"}
]
}';
$json = json_decode($read, true);
// this function will run recursively
function display($val){
// create output buffer variable
$output = "";
// check is array or not
if(is_array($val)){
// check is multimensional or not
if(isset($val[0])){
foreach($val as $v){
$output .= "<br/>".display($v);
}
}else{
foreach($val as $k => $v){
$output .= $k." => ".display($v)."<br/>";
}
}
}else{
// append output if it just a value
$output .= $val;
}
return $output;
}
echo display($json);
?>
Preview
https://code.sololearn.com/wkeim4HQO9zP#php

PHP - Array Search Not Returning Anything

Currently working on a project in C but I have to generate a large struct which I figured would generate in PHP since I'm more familiar with PHP.
I have 2 arrays. The first one is quite simple (is way larger than this but I assume this is enough to replicate the issue):
$vehicles = [
'vehicleSuper' => [ "adder", "autarch", "banshee2", "bullet" ],
'vehicleSport' => [ "alpha", "banshee", "bestiagts", "blista2" ],
//...
];
The second array looks like this:
$textures = [
'candc_apartments' => [
"limo2_b", "limo2",
],
'candc_default' => [
"marshall_flag18_b", "mesa_b", "rentbus", "marshall_flag21_b", "crusader", "boxville4", "buzzard_b", "dukes2_b", "dukes",
],
'lgm_default' => [
"hotknife", "coquette", "voltic_tless", "vacca", "infernus", "cogcabri_b", "stinger_b", "banshee_b", "ztype", "ninef", "jb700", "superd", "monroe_b", "rapidgt2_b", "khamel", "comet2_b", "cheetah_b", "rapidgt_b", "stinger", "carbon_b", "surano_convertable_b", "rapidgt2", "infernus_b", "jb700_b", "ninef_b", "stingerg", "superd_b", "bullet_b", "ztype_b", "hotknife_b", "cogcabri", "surano_convertable", "rapidgt", "stingerg_b", "coquette_b", "bullet", "carbon", "ninef2", "carboniz", "cheetah", "adder_b", "entityxf", "adder", "feltzer",
],
];
Now I generate the list like this using the 2 arrays above:
echo '<pre>';
foreach($vehicles as $category => $val) {
echo "vehicleSpawner " . $category . "[] = {\n";
foreach($val as $item) {
echo " { \"" . $item . "\", \"" . array_search($item, array_column($textures, $item)) . "\", \"\" },\n";
}
echo '}';
echo '<hr>';
}
This outputs something similar to:
{ "adder", "", "" },
The last 2 values are empty. What I want to achieve: Fill these out with the values from $textures array. In this case, I'm trying to fill it up like this:
// arg 1: name from $vehicles
// arg 2: key from $textures
// arg 3: val from $textures
{ "adder", "lgm_default", "adder" },
Currently my array_search($item, array_column($textures, $item)) method doesn't seem to work. How would I go and get this working? Help is appreciated, thanks all!
array_column($textures, $item) will search in array $textures key named $item, but there is no key with that name so it returns false, what you need to do is loop on $textures array and search if value $item exists:
foreach($val as $item) {
foreach($textures as $k => $v) {
//this will return array index or false if not exists
$pos = array_search($item, $v);
if ( $pos !== false )
echo " { \"" . $item . "\", \"" . $k . "\", \"".$v[$pos]."\" },\n";
}
}
If you want to see multiple matches within a given pair of subarrays, array_intersect() will compare both subarrays once and iterate the results. This is more efficient than running fresh array_search() calls for each element of one of the subarrays.
Code: (Demo)
foreach($vehicles as $category => $v_vals) {
echo "vehicleSpawner " . $category . "[] = {\n";
foreach($textures as $k => $t_vals) {
foreach (array_intersect($v_vals, $t_vals) as $match) {
echo " { \"$match\", \"$k\", \"$match\" },\n";
}
}
echo "}\n";
}
Output:
vehicleSpawner vehicleSuper[] = {
{ "adder", "lgm_default", "adder" },
{ "bullet", "lgm_default", "bullet" },
}
vehicleSpawner vehicleSport[] = {
}
If this isn't the exact output format/structure that you desire, it can be tweaked to accommodate.

PHP - adding only distinct value to an array in foreach loop not working

I am creating an associative array in Wordpress from user meta like this:
$users = get_users();
$allMeta = [];
foreach($users as $user) {
$allMeta[$user->ID] = get_user_meta($user->ID);
}
$metaValues = ['region', 'department', 'industry', 'company'];
$filteredMeta = [];
foreach($allMeta as $meta){
foreach($meta as $key => $value) {
if(in_array($key, $metaValues)) {
$filteredMeta[$key][] = reset($value);
}
}
}
The result of it is this array:
$filteredMeta = [
"department": [
"Administrasjon",
"Logistikk",
"Administrasjon",
"Administrasjon",
"Logistikk",
"Logistikk"
],
"region": [
"Oslo",
"Oslo",
"Oslo",
"Oslo",
"Oslo",
"Akershus"
],
"industry": [
"Bane",
"Bane",
"Bane",
"Buss",
"Buss",
"Bane"
],
"company": [
"NSB",
"NSB",
"NSB",
"NSB",
"NSB"
]
]
I have tried by getting only distinct values in that array by adding additional condition !in_array($value, $filteredMeta[$key]) in the foreach loop:
foreach($allMeta as $meta){
foreach($meta as $key => $value) {
if(in_array($key, $metaValues) && !in_array(reset($value), $filteredMeta[$key])) {
$filteredMeta[$key][] = reset($value);
}
}
}
But, that didn't work, I wouldn't get anything back, how can I achieve this?
From
$filteredMeta = [];
foreach($allMeta as $meta){
foreach($meta as $key => $value) {
if(in_array($key, $metaValues)) {
$filteredMeta[$key][] = reset($value);
}
}
}
To
$filteredMeta = [];
foreach($allMeta as $meta){
foreach($meta as $key => $value) {
// From here we modify
// we got valid value which is in list of our interest
if(in_array($key, $metaValues)) {
// some variable to save value to be added
$tmpvar = reset($value);
// status not interested call several times same function so
$status = isset($filteredMeta[$key]);
// if key does not exist in array before, meaning first time OR
// key is set, value not exists before - for duplicate check
if(
!$status ||
( $status && !in_array($tmpvar, $filteredMeta[$key]) )
){
// if key exists before then append
if($status){
$filteredMeta[$key][] = $tmpvar;
}else{
// we need to create array
$filteredMeta[$key] = array($tmpvar);
}
}
} // end of in_array
}
} // close of top foreach

Getting values out of complex Associative Array in PHP

I'm trying to integrate a 3rd party service with a Restful APi (first time doing something like this). I have managed to send the query, get a response from them, and converted it into a JSON array using:
$company_json = file_get_contents($3rdparty_url);
$company_array = json_decode($company_json, true);
The problem I'm having is getting the values out of this complex array.
This is what the array looks like:
{
"response":{
"pagination":{
"next_url":"http:\/\/someurl.org\/companies?limit=25&offset=25",
"total":33
},
"data":[
{
"id":"09934451",
"name":"Acme Incorporated"
},
{
"id":"00435820",
"name":"Acme Group Limited"
},
{
"id":"06841797",
"name":"Acme Ltd"
}
]
},
"request_id":"570bf0ca96a63"
}
I'm able to get the 'name' values out of the array by traversing it with some PHP like this:
foreach ($company_array as $data1 => $value1) {
foreach ($value1 as $data2 => $value2) {
foreach ($value2 as $data3 => $value3) {
foreach ($value3 as $data4 => $value4) {
if ($data4 == 'name') {
print $value4;
}
}
}
}
}
But what I really want to do is grab the values and put them into some sort of format like:
<ul>
<li id="09934451">Acme Incorporated</li>
<li id="00435820">Acme Group Limited</li>
<li id="06841797">Acme Ltd</li>
</ul>
From my searching around it looked like I would be able to do it with something like this, but it doesn't work. The $value4['id'] & $value4['name'], only print out the first letter of the values as if I were using $value4[0]:
foreach ($company_array as $data1 => $value1) {
foreach ($value1 as $data2 => $value2) {
foreach ($value2 as $data3 => $value3) {
foreach ($value3 as $data4 => $value4) {
print '<li id="' . $value4['id'] . '">' . $value4['name'] . '</li>';
}
}
}
}
I don't think I can be too far off but it's starting to do my head in.
Your over complicating it, it's very simple...
foreach ($company_array['response']['data'] as $data) {
echo '<li id="' . $data['id'] . '">' . $data['name'] . '</li>';
}

Categories