how to assemble data in an array by a value in php - php

i have an array like this :
[
['external_account' => 'AAA', 'label' => 'Nbr de client', 'value' => 1],
['external_account' => 'AAA', 'label' => 'TTC', 'value' => 1],
['external_account' => 'BBB', 'label' => 'HT', 'value' => 0],
]
and i want to assemble data by external_account value and have an outpout (array) like this one
[
[
'external_account' => 'AAA',
'data' => [
['label' => 'Nbr de client', 'value' => 1],
['label' => 'TTC', 'value' => 1]
]
],
[
'external_account' => 'BBB',
'data' => [
['label' => 'HT', 'value' => 0]
]
]
]
my code so far :
foreach ($result as $current_key => $current_array) {
$assemble = [];
foreach ($result as $search_key => $search_array) {
if (
$current_key != $search_key &&
$current_array["external_account"] ==
$search_array["external_account"]
) {
$valeur = $current_array["external_account"];
array_push(
$assemble,
$current_array["label"],
$current_array["value"]
);
unset($result[$current_key]);
}
$data[] = ["external_account" => $valeur, "data" => $assemble];
}
}
please tell me what am doing wrong, am stuck on it.
The output of my code : enter link description here

It looks more complicated than it needs to be. For grouping problems like this, it's just a matter of using the thing you want to group by as a key as you build your result.
$result = [];
foreach ($data as $item) {
// extract the first key (external_account)
$account = array_shift($item);
// then use it as the key to group your data
$result[$account]['external_account'] = $account;
$result[$account]['data'][] = $item;
}
If you don't want to keep that key in your result, you can remove it with
$result = array_values($result);

Related

Remove a array from an multidimensional array using object value in laravel

i need to remove duplicate array from below array.
first and third arrays are same, consider only "id"
$data = [
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
],
[
'id' => 'test_fun1%test',
'text' => 'test_fun1',
'data-value' => 'test',
],
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
'selected' => true
]
];
i'm tried to below code.
-> array_unique($data);
-> array_map("unserialize", array_unique(array_map("serialize", $data)));
Expected Output
$data = [
[
'id' => 'test_fun1%test',
'text' => 'test_fun1',
'data-value' => 'test',
],
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
'selected' => true
]
];
array_unique is not going to work since you have "selected" in the third array. I agree with the comments that this is quite unclear but to me it seems you're looking for a custom filtration rule, so a plain old foreach is the tool for the job.
<?php
$data = [
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
],
[
'id' => 'test_fun1%test',
'text' => 'test_fun1',
'data-value' => 'test',
],
[
'id' => 'test_fun%test',
'text' => 'test_fun',
'data-value' => 'test',
'selected' => true
]
];
$filtered = [];
foreach ($data as $row) {
$id = $row['id'];
$selected = $row['selected'] ?? false;
if (isset($filtered[$id])) {
if (!$selected) {
continue;
}
unset($filtered[$id]);
}
$filtered[$id] = $row;
}
// optional use if you don't want ids for keys
$filtered = array_values($filtered);
print_r($filtered);

How to convert an array as follows?

I have an array
[
[
'title' => 'title0',
'data' => 'data0'
],
[
'title' => 'title1',
'data' => 'data1'
]
]
I need to get the output
[
'title' => ['title0','title1'],
'data' => ['data0', 'data1']
]
Please tell me how can I do this?
You didn't show any attempt, but I'm bored. Just loop the keys from the first sub-array and extract that column. No need to know what the keys are:
foreach(array_keys(reset($array)) as $key) {
$result[$key] = array_column($array, $key);
}
You could also do it this way:
foreach(reset($array) as $key => $val) {
$result[$key] = array_column($array, $key);
}
Or if it's as simple as those two known keys:
$result = ['title' => array_column($array, 'title'),
'data' => array_column($array, 'data')
];
You can do it like this
<?php
$shortedArray = [
'title' => [],
'data' => []
];
$mainArray = [
[
'title' => 'test0',
'data' => 'data0'
],
[
'title' => 'test1',
'data' => 'data1'
]
];
// Loop thru it
foreach($mainArray as $row){
$shortedArray['title'][] = $row['title'];
$shortedArray['data'][] = $row['data'];
}
print_r($shortedArray);
Hope this resolves your issue. Any query, let me know

PHP merge duplicate key in array

i got response (json) from web service and converted / decoded it into php array.
converted array php:
$data = [
[
'id' => '01',
'name' => 'ABC',
'label' => 'color',
'value' => '#000000'
],[
'id' => '01',
'name' => 'ABC',
'label' => 'active',
'value' => true
],[
'id' => '02',
'name' => 'DEF',
'label' => 'color',
'value' => '#ffffff'
],[
'id' => '02',
'name' => 'DEF',
'label' => 'active',
'value' => false
]
];
expected array output:
$data = [
[
'id' => '01',
'name' => 'ABC',
'color' => '#000000',
'active' => true,
],[
'id' => '02',
'name' => 'DEF',
'color' => '#ffffff',
'value' => false
]
];
What php function is suitable for that case? thanks in advance
You can simple use foreach
$r = [];
foreach($data as $v){
if(isset($r[$v['id']])){
$r[$v['id']][$v['label']] = $v['value'];
}else{
$r[$v['id']] = [
'id' => $v['id'],
'name' => $v['name'],
$v['label'] => $v['value']
];
}
}
Live example : https://3v4l.org/ilkGG
$data = json_decode($data); //decode the json into a php array
foreach ($data as $key=>$subArray){ //loop over the array
//check and see if value is either true/false
if (is_bool($subArray['value'])){
$processedArray[] = $subArray; //build output
}
}
print_r($processedArray); //output/dump array for debugging
In this case, you have to loop through the array and remove duplicates, Try the given way
$data = json_decode($data , true);
$filtered = array();
for($i = 0 ; $i < count($data) ; $i++){
if(!array_key_exist($data[$i]['id'] , $filtered )){
$filtered [$data[$i]['id']] = $data[$i];
continue;
}
}
$filtered = array_values($filtered);

Need to push the key and value inside associative Array?

I need to push the more key and its value inside the array. If I use below code first key pair replaced by 2nd one.
For your Reference:
Code Used:
foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
}
Current result:
'projectsections' => [
(int) 0 => [
'id' => '1'
],
(int) 1 => [
'id' => '1'
]
],
Expected:
'projectsections' => [
(int) 0 => [
'name' => 'test1',
'id' => '1'
],
(int) 1 => [
'name' => 'test2',
'id' => '1'
]
],
How can I build this array in PHP?? Any one help??
You need to either add the entire array:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
Or add with the key name:
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
With
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
you are setting a new Array for that $key. This is not what you want.
This should work:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
Change it to :
foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
}

Recursively Create an Array from another Array

I am trying to make a multi-dimensional array build an array path adding the hr field so it looks like this:
I just can't figure out how to add the totals, nor create a sub-array so the dot notation in an option too. My goal is to get something like this:
[1] => [1][2][1][5][0][6] = 35 (the second child path "1")
[1] => [1][2][1][5][0][7] = 25
or Something like this:
array (
[children.0.children.0.children.0.total] = 20
[children.0.children.1.children.1.total] = 35
// etc
)
The complicated part is that it goes in different directions and I want to know what is the highest and lowest total based on the path:
==> Run Code Here or Copy/Paste
// -------------
// The Flattener
// -------------
function doit($myArray) {
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($myArray));
$result = array();
foreach ($iter as $leafKey => $leafValue) {
$keys = array();
foreach (range(0, $iter->getDepth()) as $depth) {
$keys[] = $iter->getSubIterator($depth)->key();
}
$result[ join('.', $keys) ] = $leafValue;
}
return $result;
}
// -------------
// Example Tree
// -------------
$tree = [
'id' => 1,
'type' => 'note',
'data' => [],
'children' => [
[
'id' => 2,
'type' => 'wait',
'data' => [
'hr' => 10,
],
'children' => [
[
'id' => 3,
'type' => 'wait',
'data' => [
'hr' => 10,
],
'children' => [
'id' => 4,
'type' => 'exit',
'data' => [],
'children' => []
]
],
[
'id' => 5,
'type' => 'note',
'data' => [
'hr' => 10,
],
'children' => [
[
'id' => 6,
'type' => 'wait',
'data' => [
'hr' => 10,
],
'children' => []
],
[
'id' => 7,
'type' => 'exit',
'data' => [],
'children' => []
],
]
]
],
]
]
];
$result = doit($tree);
print_r($result);
This seems to work, I found it somewhere googling all day.
array_reduce(array_reverse($keys), function($parent_array, $key) {
return $parent_array ? [$key => $parent_array] : [$key];
}, null);

Categories