Get value from array have a multirows - php

I Have this array and i want to get all parent have a balance :
this array is multi rows note that sub-array is not static could be more
Thanks
$array_content = [
'id'=> 4,
'Parent' => [
[
'id' => 54,
'Parent' => [
[
'id' => 324,
'KUI' => 'ABC',
'figure' => 'Tira',
'Parent'=> []
],
[
'id' => 52355,
'lft' => 'LEFT',
'Parent' => [
[
'id' => 4,
'Parent' => [
[
'id' => 234,
'ui' => 'UITed',
'Parent'=> ['Balance'=>450.3]
]
]
],
[
'id' => 76,
'ui' => 'some value',
'Parent'=> []
]
],
]
],
],
[
'id' => 23,
'title' => 'ABC',
'Parent' => [
],
]
]
];
The output that i need to see is this balance by the id =234 from parent:
'Balance'=>450.3

You can also, instead of iterating the array, make it Json and use substr and strpos (or regex) to find the value.
$json = json_encode($array_content);
$pos = strpos($json, "Balance\":")+9; // +9 for Balance": is 9 characters
Echo substr($json, $pos, strpos($json, "}", $pos)-$pos); // 450.3
https://3v4l.org/cojXe

Here i found the answer Thanks everyone :
$array_content = [
'id'=> 4,
'Parent' => [
[
'id' => 54,
'Parent' => [
[
'id' => 324,
'KUI' => 'ABC',
'figure' => 'Tira',
'Parent'=> []
],
[
'id' => 52355,
'lft' => 'LEFT',
'Parent' => [
[
'id' => 4,
'Parent' => [
[
'id' => 234,
'ui' => 'UITed',
'Parent'=> ['Balance'=>450.3]
]
]
],
[
'id' => 76,
'ui' => 'some value',
'Parent'=> []
]
],
]
],
],
[
'id' => 23,
'title' => 'ABC',
'Parent' => [
],
]
]
];
function search($arr,$id)
{
if(gettype($arr) == 'array')
foreach($arr as $key =>$list)
{
if(gettype($list) == 'array'){
if(isset($list['id']))
{
if($list['id'] ==$id)
print_r($list['Parent']);
}
search($list,$id);
}
}
}
foreach($array_content as $key)
{
search($key,234);
}

Related

Sorting an array by text of first subarray in each row

I have an array stored as $product_categories. A sample of this array is:
$array = [
[
['id' => 10, 'text' => 'Latex'],
['id' => 15, 'text' => 'Occasion Latex'],
['id' => 82, 'text' => 'Christmas'],
],
[
['id' => 11, 'text' => 'Accessories'],
['id' => 97, 'text' => 'Retail Accessories'],
['id' => 558, 'text' => 'Super Stuffer'],
],
[
['id' => 374, 'text' => 'Party Supplies'],
['id' => 1488, 'text' => 'Party by Occasion'],
['id' => 1493, 'text' => 'Christmas'],
],
];
I want to sort it ONLY by the key 'text' in [0], which would give me a result of
[
[
['id' => 11, 'text' => 'Accessories'],
['id' => 97, 'text' => 'Retail Accessories'],
['id' => 558, 'text' => 'Super Stuffer'],
],
[
['id' => 10, 'text' => 'Latex'],
['id' => 15, 'text' => 'Occasion Latex'],
['id' => 82, 'text' => 'Christmas'],
],
[
['id' => 374, 'text' => 'Party Supplies'],
['id' => 1488, 'text' => 'Party by Occasion'],
['id' => 1493, 'text' => 'Christmas'],
],
];
I've tried using
$product_categories = usort($product_categories, 'sortAlphabetically');
function sortAlphabetically($a, $b) {
return strcmp($a['text'], $b['text']);
}
Using that, a print_r() of the array simply returns
1.
I thought usort() was the correct way to sort the array but clearly I'm doing something wrong here.
You only need to access the subarray data using array syntax as you've expressed in English. (Demo)
usort(
$array,
function($a, $b) {
return $a[0]['text'] <=> $b[0]['text'];
}
);
var_export($array);
Or in PHP7.4 or higher:
usort($array, fn($a, $b) => $a[0]['text'] <=> $b[0]['text']);
Your array:
$array = [
'0' => [
'0' => [
'id' => 10,
'text' => 'Latex',
],
'1' => [
'id' => 15,
'text' => 'Occasion Latex',
],
'2' => [
'id' => 82,
'text' => 'Christmas',
],
],
'1' => [
'0' => [
'id' => 11,
'text' => 'Accessories',
],
'1' => [
'id' => 97,
'text' => 'Retail Accessories',
],
'2' => [
'id' => 558,
'text' => 'Super Stuffer',
],
],
'2' => [
'0' => [
'id' => 374,
'text' => 'Party Supplies',
],
'1' => [
'id' => 1488,
'text' => 'Party by Occasion',
],
'2' => [
'id' => 1493,
'text' => 'Christmas',
],
],
];
The sort:
// uasort(): "Sort an array with a user-defined comparison function
// and maintain index association"
uasort($array, function (array $a, array $b) {
// "I want to sort it ONLY by the key 'text' in [0]"
// Get first from array (aka [0]).
// (You could change that to fix $a[0] and $b[0] if you want|need to.)
$aFirst = reset($a);
$bFirst = reset($b);
$offset = 'text';
if ($aFirst[$offset] == $bFirst[$offset]) {
return 0;
}
// a < b === asc ; a > b === desc
return ($aFirst[$offset] < $bFirst[$offset]) ? -1 : 1;
});
echo var_export($array, true) . PHP_EOL;
Results in:
[
1 => [
0 => [
'id' => 11,
'text' => 'Accessories',
],
1 => [
'id' => 97,
'text' => 'Retail Accessories',
],
2 => [
'id' => 558,
'text' => 'Super Stuffer',
],
],
0 => [
0 => [
'id' => 10,
'text' => 'Latex',
],
1 => [
'id' => 15,
'text' => 'Occasion Latex',
],
2 => [
'id' => 82,
'text' => 'Christmas',
],
],
2 => [
0 => [
'id' => 374,
'text' => 'Party Supplies',
],
1 => [
'id' => 1488,
'text' => 'Party by Occasion',
],
2 => [
'id' => 1493,
'text' => 'Christmas',
],
],
]

Unsetting nested descendants of a particular ancestor based on an key and if empty unset the ancestor as well

Let's imagine we have this multidimensional array which contains nested arrays
$arr = [
1 => [
'id' => 1,
'families' => [
0 => [
'id' => 2
],
1 => [
'id' => 3
],
]
],
2 => [
'id' => 1,
'families' => [
0 => [
'id' => 2,
'products' => [
1 => 'John Doe'
],
],
1 => [
'id' => 3,
'products' => [],
],
]
],
3 => [
'id' => 1,
'products' => [
1 => 'Hi',
2 => 'Hello',
]
],
4 => [
'id' => 1,
'families' => [
0 => [
'id' => 2
],
1 => [
'id' => 3
],
]
],
];
I need to keep all ancestors and descendants where there is at least one item in the key "products", all other arrays should be unset.
So, in this particular example, the result should be as follows:
$arr = [
2 => [
'id' => 1,
'families' => [
0 => [
'id' => 2,
'products' => [
1 => 'John Doe'
],
],
]
],
3 => [
'id' => 1,
'products' => [
1 => 'Hi',
2 => 'Hello',
]
],
];
Basically, what needs to be done is to go from the most inner array up and asking:
1) Is our key "products" empty? Yes
2) Is our key "families" either empty or not set? Yes
3) unset this array
You can do it like this:
<?php
$arr = [
1 => [
'id' => 1,
'families' => [
0 => [
'id' => 2
],
1 => [
'id' => 3
],
]
],
2 => [
'id' => 1,
'families' => [
0 => [
'id' => 2,
'products' => [
1 => 'John Doe'
],
],
1 => [
'id' => 3,
'products' => [],
],
]
],
3 => [
'id' => 1,
'products' => [
1 => 'Hi',
2 => 'Hello',
]
],
4 => [
'id' => 1,
'families' => [
0 => [
'id' => 2
],
1 => [
'id' => 3
],
]
],
];
foreach($arr as $k => $a) {
if(strpos(json_encode($a), "products") == 0){
unset($arr[$k]);
}
}
var_dump($arr);
https://3v4l.org/tNSqs

How to get particular nested array based on the given matched key?

How to get particular nested array based on the given matched key using PHP built in function
Scenario
$id = 1035; // Searching ID
$a = [
'id'=> 291,
'children' => [
[
'id' => 1034,
'children' => [
[
'id' => 111,
'name' => 'ABC',
'figure' => '6 digits',
'children'=> []
],
[
'id' => 1035,
'lft' => 'LEFT',
'children' => [
[
'id' => 1036,
'children' => [
[
'id' => 222,
'someKey' => 'some value',
'children'=> []
]
]
],
[
'id' => 333,
'someKey' => 'some value',
'children'=> []
]
],
]
],
],
[
'id' => 1024,
'title' => 'ABC',
'children' => [
],
]
]
];
Please note, 'id' & 'children' keys are always be there. How to get the "children" of "1035" ID..?
Expected Output
[
[
'id' => 1036,
'children' => [
[
'id' => 222,
'someKey' => 'some value',
'children'=> []
]
],
],
[
'id' => 333,
'someKey' => 'some value',
'children'=> []
]
];
Tried
function getRecursiveCategoryIds($key, $categories = []){
$return = null;
try {
array_walk_recursive($categories, function($v, $k) use ($key, &$return){
if (null != $return) {
// Run loop to get the next immediate "children" key
if ($k == 'children') { // It's not matching anymore
$return = $v;
//return false;
throw new Exception;
}
} else if($v == $key) {
// Found
$return = $v;
}
});
} catch(Exception $e) {}
return $return;
}
$d = getRecursiveCategoryIds($id, $a);
echo '<pre>D: '; print_r($d); die;
I tried by the above code, but the "if ($k == 'children') {" is not matched any more..!
Any suggestions are welcome... (PHP's Built in function is most prefer!)
I was able to do this. Please check the comments in the code:
<?php
$id = 1035; // Searching ID
$myObj = array();
$a = [
'id'=> 291,
'children' => [
[
'id' => 1034,
'children' => [
[
'id' => 111,
'name' => 'ABC',
'figure' => '6 digits',
'children'=> []
],
[
'id' => 1035,
'lft' => 'LEFT',
'children' => [
[
'id' => 1036,
'children' => [
[
'id' => 222,
'someKey' => 'some value',
'children'=> []
]
]
],
[
'id' => 333,
'someKey' => 'some value',
'children'=> []
]
],
]
],
],
[
'id' => 1024,
'title' => 'ABC',
'children' => [
],
]
]
];
function findObject($id, $obj) {
global $myObj;
// This is an object.
if (isset($obj["id"])) {
echo "Checking {$obj["id"]}<br />";
// Check the id to what we need.
if ($obj["id"] == $id) {
// Yay! We found it. Return the object.
echo "Yay we found {$obj["id"]}<br />";
$myObj = $obj;
}
else {
echo "Checking children of {$obj["id"]}<br />";
// See if it has any children
if (isset($obj["children"]) && count($obj["children"]) > 0) {
echo "There are children for {$obj["id"]}<br />";
foreach ($obj["children"] as $child) {
findObject($id, $child);
}
}
}
}
}
findObject($id, $a);
print_r($myObj);
Output
Checking 291Checking children of 291There are children for 291Checking 1034Checking children of 1034There are children for 1034Checking 111Checking children of 111Checking 1035Yay we found 1035Need to find a way to break out!Checking 1024Checking children of 1024Found it!Array
(
[id] => 1035
[lft] => LEFT
[children] => Array
(
[0] => Array
(
[id] => 1036
[children] => Array
(
[0] => Array
(
[id] => 222
[someKey] => some value
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 333
[someKey] => some value
[children] => Array
(
)
)
)
)
Demo:
https://ideone.com/UoKqrU
https://3v4l.org/rWkPq
You can use function inside other check :
$id=1035;
$a = [
'id'=> 291,
'children' => [
[
'id' => 1034,
'children' => [
[
'id' => 111,
'name' => 'ABC',
'figure' => '6 digits',
'children'=> []
],
[
'id' => 1035,
'lft' => 'LEFT',
'children' => [
[
'id' => 1036,
'children' => [
[
'id' => 222,
'someKey' => 'some value',
'children'=> []
]
]
],
[
'id' => 333,
'someKey' => 'some value',
'children'=> []
]
],
]
],
],
[
'id' => 1024,
'title' => 'ABC',
'children' => [
],
]
]
];
function nigsearch($arr,$id)
{
if(gettype($arr) == 'array')
foreach($arr as $key =>$list)
{
if(gettype($list) == 'array'){
if(isset($list['id']))
{
if($list['id'] ==$id)
print_r($list['children']);
}
nigsearch($list,$id);
}
}
}
foreach($a as $key)
{
nigsearch($key,$id);
}

Query get data from database change to array

I want to make a chart, I have database province and I want to make this be xAxis on Highcharts.
My Database
<?= \dosamigos\highcharts\HighCharts::widget([
'clientOptions' => [
'chart' => [
'type' => 'spline'
],
'title' => [
'text' => 'Fruit Consumption'
],
'xAxis' => [
'categories' => [
'Jabodetabek',
'Banten',
'Jawa Tengah',
'Jawa Timur',
'Medan',
'Riau',
'Bangka Belitung',
'Lampung',
'Kalimantan Selatan',
'Kalimantan Barat',
'Kalimantan Timur',
'Kalimantan Tengah',
'NTB',
'NTT',
'Papua']
],
'yAxis' => [
'title' => [
'text' => 'Fruit eaten'
]
],
'plotOptions' => [
'line' => [
'dataLabels' => [
'enabled'=> true
]
]
],
'series' => [
['data' => [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
],
'responsive' => [
'rules' => [[
'condition' => [
'maxWidth' => 500
],
'charOptions' => [
'legend' => [
'align' => 'center',
'verticalAlign' => 'bottom',
'layout' => 'horizontal'
],
'yAxis' => [
'labels' => [
'align' => 'left',
'x' => 0,
'y' => 0
],
'title' => [
'text' => null
]
]
]
]]
]
]
]);
How can I make the contents of the province table be an array? I want data count all group by provinces.
Please help me
The yii2-friendly method is to use gii to generate models for each of your tables. Then you can get an array like
$provinces = \app\models\Province::find()->select('name')->asArray();
You can use a similar technique to get the count; I'd post an example except I'm not sure what the correct sql would be for your case.

PHP Branching Recursion With Repeating Children

I have a flat structure that I need to convert to a nested tree-like structure. This is different from other Stack Overflow questions because the children can repeat (i.e. can have the same questionId and parentId). I have attempted to solve this with branching recursion with no luck.
Input (flat array):
[
[
'questionId' => 1,
'name' => 'albumName',
'parentId' => 0,
'answer' => "Name of album",
],
[
'questionId' => 2,
'name' => 'albumGenre',
'parentId' => 0,
'answer' => "album genre",
],
[
'questionId' => 3,
'name' => 'trackStart',
'parentId' => 0,
],
[
'questionId' => 4,
'name' => 'trackName',
'parentId' => 3,
'answer' => "Track One",
],
[
'questionId' => 5,
'name' => 'trackEnd',
'parentId' => 3,
],
[
'questionId' => 3,
'name' => 'trackStart',
'parentId' => 0,
],
[
'questionId' => 4,
'name' => 'trackName',
'parentId' => 3,
'answer' => "Track Two",
],
[
'questionId' => 6,
'name' => 'artistStart',
'parentId' => 3,
],
[
'questionId' => 7,
'name' => 'artistName',
'parentId' => 6,
'answer' => "Artist Name",
],
[
'questionId' => 8,
'name' => 'artistEnd',
'parentId' => 6,
],
[
'questionId' => 5,
'name' => 'trackEnd',
'parentId' => 3,
],
[
'questionId' => 9,
'name' => 'albumDate',
'parentId' => 0,
'answer' => "album Date",
]
]
Desired Output (nested array):
[
'albumName' => 'Album Name',
'albumGenre' => 'Album Genre',
'trackStart' => [
[
'trackName' => 'Track One'
],
[
'trackName' => 'Track Two',
'artistStart' => [
[
'artistName' => 'Artist Name'
]
]
]
],
'albumDate' => 'album Date'
]
You can solve this using Reference Pointers:
$newArray = array();
$pointer[] = &$newArray;
foreach($arr as $ar) {
if(stristr($ar['name'], "start")) { // Start
$pointer[] = &$pointer[count($pointer)-1][$ar['name']][];
} else if(stristr($ar['name'], "end")) { // End
array_pop($pointer);
} else {
$pointer[count($pointer)-1][$ar['name']] = $ar['answer'];
}
}
To make it faster you can use stripos($ar['name'], "start") !== false;

Categories