I got this array named $records:
Array
(
[0] => Array
(
[id] => 14
[name] => name1
[publisher] => Dieter
[date] => 2022-07-29
[text] => blablablablablablablablablabblablablablablablablablablablablablablablabla
)
[1] => Array
(
[id] => 16
[name] => name2
[publisher] => Dieter
[date] => 2022-07-28
[text] => awhduawohduawohduawhduawuhdawhduaiwd
)
[2] => Array
(
[id] => 17
[name] => name3
[publisher] => Dieter
[date] => 2022-07-30
[text] => blub
)
[3] => Array
(
[id] => 18
[name] => name4
[publisher] => Dieter
[date] => 2022-07-31
[text] => awdawdw
)
)
and then I want to filter them by their ids($ids=[14,16]):
$articles = array();
foreach ($records as $article) {
if (in_array($article['id'], $ids)) { //alg select only one article
$articles = array_merge($articles, $article);
}
}
return $articles;
and the Output should look like this:
Array
(
[0] => Array
(
[id] => 14
[name] => name1
[publisher] => Dieter
[date] => 2022-07-29
[text] => blablablablablablablablablabblablablablablablablablablablablablablablabla
)
[1] => Array
(
[id] => 16
[name] => name2
[publisher] => Dieter
[date] => 2022-07-28
[text] => awhduawohduawohduawhduawuhdawhduaiwd
)
)
But I got this:
Array
(
[id] => 16
[name] => name2
[publisher] => Dieter
[date] => 2022-07-28
[text] => awhduawohduawohduawhduawuhdawhduaiwd
)
This command doesnt work because I get a diffrent structure:
array_merge_recursiv()
$articles = array();
foreach ($records as $article) {
if (in_array($article['id'], $ids)) { //alg select only one article
$articles[] = $article;
}
}
return $articles;
array_merge is not needed here, you can push a new entry in your table using $articles[].
You can also keep keys of the original table like that :
$articles = array();
foreach ($records as $key => $article) {
if (in_array($article['id'], $ids)) { //alg select only one article
$articles[$key] = $article;
}
}
return $articles;
function array_diff_column_values($rawArray, $searchArray, $columnName = 'id') {
$result = [];
foreach($rawArray as $key => $value) {
if (isset($value[$columnName]) && in_array($value[$columnName], $searchArray)) {
$result[] = $value;
}
}
return $result;
}
echo "<pre>";
print_r(array_diff_column_values($records, [14,16]));
echo "</pre>";
Related
i have array like this:
(
[0] => Array
(
[id] => 1
[name] => Bazowa
[parent_id] => 0
)
[1] => Array
(
[id] => 2
[name] => Główna
[parent_id] => 1
)
[2] => Array
(
[id] => 12
[name] => PlayStation
[parent_id] => 2
)
[3] => Array
(
[id] => 13
[name] => Xbox
[parent_id] => 2
)
[4] => Array
(
[id] => 14
[name] => Nintendo
[parent_id] => 2
)
[5] => Array
(
[id] => 15
[name] => PC
[parent_id] => 2
)
)
and i want sort this array like tree on screenshot below:
Screen of tree what I want
i trying use this Sort array values based on parent/child relationship
foreach($xml->children()->children() as $value) {
if($value->active == 1) {
$categories[] = [
'id' => (int) $value->id,
'name' => (string) $value->name->language,
'parent_id' => (int) $value->id_parent
];
}
}
$parent_ids = [];
$parents = ['' => []];
foreach($categories as $val) {
$parents[$val['parent_id']][] = $val;
}
$sorted = $parents[''];
dump($parents); exit;
for($val = reset($sorted); $val; $val = next($sorted)) {
if(isset($parents[$val[0]])) {
foreach($parents[$val[0]] as $next) {
$sorted[] = $next;
}
}
}
The most important thing for me is that everything displays well in select, which is something like this:
-Playstation
-- Playstation 5
--- Gry
--Playstation 3
--- Gry
Anyone can help me?
EDIT:
Problem solved by Build a tree from a flat array in PHP
This should work
usort($arr, function($a, $b) {
return $a["parent_id"] > $b["parent_id"];
});
I am working with soap responses that contain nested wrappers and whose child(ren) have nested properties.
I am trying to flatten these response to:
remove the wrappers
flatten the children
maintain the individual children (dimensions)
I am currently working with the following that achieves #1 and #3 however it does not flatten the inner children. Note that $this->response is converted from a stdClass to Array before being flattened.
How can I also flatten down the inner nested child elements?
private function toArray()
{
$this->response = json_decode(json_encode($this->response), true);
return $this;
}
private function flatten($array = null)
{
if (is_null($array)) {
$array = $this->response;
}
if (is_array($array)) {
foreach ($array as $k => $v) {
if (count($v) == 1 && is_array($v)) {
return $this->flatten($v);
}
if (isset($v[0])) {
$this->response = $v;
return $this;
}
unset($this->response);
$this->response[] = $v;
return $this;
}
}
}
...which will transform this:
stdClass Object
(
[ArrayOfDevice] => stdClass Object
(
[Device] => Array
(
[0] => stdClass Object
(
[NamedElement] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => DEVICE
[id] => Device1ID
)
[name] => Device1
)
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => stdClass Object
(
[NamedElement] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => DEVICE
[id] => Device2ID
)
[name] => Device2
)
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
)
)
...to this:
Array
(
[0] => Array
(
[NamedElement] => Array
(
[Element] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
)
[name] => Device1
)
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[NamedElement] => Array
(
[Element] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
)
[name] => Device2
)
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
...but I'd prefer:
Array
(
[0] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
[name] => Device1
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
[name] => Device2
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
...and in the case of a single item being returned, this:
stdClass Object
(
[ArrayOfAlarm] => stdClass Object
(
[Alarm] => stdClass Object
(
[Element] => stdClass Object
(
[ElementType] => ALARM
[id] => Alarm1ID
)
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
)
...to this:
Array
(
[0] => Array
(
[Element] => Array
(
[ElementType] => ALARM
[id] => Alarm1ID
)
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
...but I'd prefer:
Array
(
[0] => Array
(
[ElementType] => ALARM
[id] => Alarm1ID
[activeTime] =>
[AlarmSeverity] =>
[AlarmState] =>
[description] =>
[deviceID] =>
[recommendedAction] =>
[resolvedTime] =>
[sensorID] =>
)
)
You can flatten a single of your items with the following function:
function flatten_item($array)
{
$result = [];
foreach ($array as $k => $v) {
if (is_array($v)) {
$result = array_merge($result, $this->flatten_item($v));
} else {
$result[$k] = $v;
}
}
return $result;
}
When you have an array of results, you can pass this function as the callback to array_map. Only the relevant portion of the code:
if (isset($v[0])) {
$this->response = array_map([$this, 'flatten_item'], $v);
return $this;
}
// Convert single result to an array
$this->response = [$this->flatten_item($v)];
return $this;
Since the response (so far) always has the same structure, you could extract the payload without using recursion, which allows you to also remove the foreach in the flatten function:
function flatten()
{
// Remove outer wrappers [ArrayOfX][X] by extracting the value
$payload = current(current($this->response));
if (isset($payload[0])) {
$this->response = array_map([$this, 'flatten_item'], $payload);
} else {
$this->response = [$this->flatten_item($payload)];
}
return $this;
}
The function found here does just what you want, with a slight modification (commented out concatination of parent keys): https://gist.github.com/kohnmd/11197713#gistcomment-1895523
function flattenWithKeys(array $array, $childPrefix = '.', $root = '', $result = array()) {
foreach($array as $k => $v) {
if(is_array($v) || is_object($v)) $result = flattenWithKeys( (array) $v, $childPrefix, $root . $k . $childPrefix, $result);
else $result[ /*$root .*/ $k ] = $v;
}
return $result;
}
Letting $object equal your provided object, use as follows:
$array = json_decode(json_encode($object), true);
$result =[];
foreach( $array['ArrayOfDevice']['Device'] as $key => $value ){
$result[$key] = flattenWithKeys($value);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[ElementType] => DEVICE
[id] => Device1ID
[hostName] => Device1.hostname
[ipAddress] => Device1.ip
[location] => location1
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 123456789
)
[1] => Array
(
[ElementType] => DEVICE
[id] => Device2ID
[name] => Device2
[hostName] => Device2.hostname
[ipAddress] => Device2.ip
[location] => location2
[modelName] =>
[modelNumber] =>
[parentID] => xxxYYY
[serialNumber] => 987654321
)
)
See it run here: http://sandbox.onlinephpfunctions.com/code/851e93389b993a0e44c1e916291dc444f47047d3
How can I create a function to display an array as a tree. For example I want to obtain a decision tree which I want to walk until I get to the leafs based on the branch's values. I create the tree like bellow:
$tree= new DS_Tree();
$node=array('name' => 'start');
$tree->insert_node($node);
$tree->goto_root();
$mytree = new id3();
$mytree->init($data_array_AttrList,$data_array_values,$data_class,$data_array_instances,$tree);
$mytree->run();
echo '<pre class="brush: php">';
print_r($mytree->tree->draw_tree());
echo '</pre>';
The function draw_tree() is:
public function draw_tree() {
return $this->nodes;
}
The function that creates my tree is:
private function make_tree($attr) {
foreach($this->Values[$attr] as $v) {
$subset = $this->get_subset($attr, $v);
if($the_class = $this->has_same_class($subset)) {
$node =array(
'name' => $attr,
'arc' => $v
);
$this->tree->insert_node($node);
$this->Instance = array_diff_key($this->Instance, $subset);
} else {
$node =array(
'name' => $this->Classa,
'arc' => $v
);
$unresolved = $this->tree->insert_node($node);
}
}
if (isset($unresolved)) {
$this->tree->goto_index($unresolved);
}
}
}
The result is:
Array
(
[0] => Array
(
[name] => Time
[parent] =>
[children] => Array
(
[0] => 1
)
)
[1] => Array
(
[name] => Focus
[arc] => Array
(
[0] => 2 day/week
[1] => 3 day/week
[2] => 4 day/week
[3] => 5 day/week
[4] => 6 day/week
)
[parent] => 0
[children] => Array
(
[0] => 2
)
)
[2] => Array
(
[name] => Dificulty
[arc] => Array
(
[0] => Weght loss
[1] => Mantain weight
[2] => Gain Mass
)
[parent] => 1
[children] => Array
(
[0] => 3
)
)
[3] => Array
(
[name] => Sex
[arc] => Array
(
[0] => Beginner
[1] => Intermediar
[2] => Advance
)
[parent] => 2
[children] => Array
(
[0] => 4
)
)
[4] => Array
(
[name] => Array
(
[Exercise] => Array
(
[0] => Array
(
[0] => Ex1
[1] => Ex2
[2] => Ex3
[3] => Ex4
[4] => Ex5
)
)
)
[arc] => Array
(
[0] => F
[1] => M
)
[parent] => 3
)
)
Just to display an array as a tree:
echo "<pre>";
var_dump($array);
echo "</pre>";
Here is a way to iterate through this data structure and look for a certain value:
function recurseFind($tree, $find, $path = "") {
if (!is_array($tree)) {
// it is a leaf:
if ($tree === $find) {
return $path; // return path where we found it
}
return false;
}
foreach($tree as $key => $value) {
$result = recurseFind($value, $find, $path . (is_numeric($key) ? "[$key]" : "['$key']"));
if ($result !== false) return $result;
}
return false;
}
For the sample input you provided, if you would call it like this:
echo recurseFind($tree, "Mantain weight", '$tree');
Outputs the "location" of that value (first match only) in a format that can be evaluated in PHP:
$tree[2]['arc'][1]
Could this be possible? How to combine or merge arrays in php. to fetch data individualy for echoing purpose. Could this be possible? How to combine or merge arrays in php. to fetch data individualy for echoing purpose.
Array(
[0] => stdClass Object
(
[id] => 1
[icd] => J96.0
[rank] => 1
[description] => Acute respiratory failure
)
[1] => stdClass Object
(
[id] => 1
[icd] => J44.1
[rank] => 2
[description] => Chronic obstructive pulmonary disease with (acute) exacerbation
)
[2] => stdClass Object
(
[id] => 1
[icd] => J18.9
[rank] => 3
[description] => Pneumonia, unspecified organism
)
)
To this
Array(
[id] => 1
[icd] => (
[0] => J96.0
[1] => J44.1
[2] => J18.9
)
[description] => (
[0] => Acute respiratory failure
[1] => Chronic obstructive pulmonary disease with (acute) exacerbation
[2] => Pneumonia, unspecified organism
)
)
USe This
array_merge_recursive
Follow Link
Link With Example
$new_array = array();
foreach($your_array as $row){
$new_array['id'] = $row->id;
$new_array['icd'][] = $row->icd;
$new_array['description'][] = $row->description;
}
print_r($new_array);
$output = array();
$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
$keys = array("id", "icd", "rank", "description");
foreach ($keys as $key) {
$currKey = $value[$key];
if ( !isset($output[$currKey]) ) {
$output[$currKey] = array();
}
$output[$currKey] = array_merge($output[$currKey], $value);
}
}
var_dump($output);
I have array result like this:
Array
(
[0] => stdClass Object
(
[id_global_info] => 78
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:54
[date_expires] => 2012-04-14 16:11:54
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[1] => stdClass Object
(
[id_global_info] => 79
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
[2] => stdClass Object
(
[id_global_info] => 80
[name] => rfhd
[body] => dhfdhdf
[contact_author] => mirko
[date_created] => 2012-03-15 16:11:56
[date_expires] => 2012-04-14 16:11:56
[email] =>
[location_id] => 1
[category_id] => 26
[tag] => fhdhfdhfd
[info_type_id] => 4
[user_id] => 3
)
.
.
.
)
How can I search a multidimensional array and count number of results (for example I want to search for info_type_id with value of 4)?
Use array_filter to filter the array:
function test($arr) {
return $arr["info_type_id"] == 4;
}
echo count(array_filter($yourArray, "test"));
with foreach ?
function searchMyCoolArray($arrays, $key, $search) {
$count = 0;
foreach($arrays as $object) {
if(is_object($object)) {
$object = get_object_vars($object);
}
if(array_key_exists($key, $object) && $object[$key] == $search) $count++;
}
return $count;
}
echo searchMyCoolArray($input, 'info_type_id', 4);
You should try this :
$counter = 0;
$yourArray; // this var is your current array
foreach($yourArray as $object){
if($object->info_type_id == 4){
$counter++;
}
}