I have an array structure like this
Array
(
[0] => stdClass Object
(
[foo] => 9992
[bar] => 1508
)
[1] => stdClass Object
(
[foo] => 10115
[bar] => 1598
)
[2] => stdClass Object
(
[foo] => 10263
[bar] => 1690
)
[3] => stdClass Object
(
[foo] => 10363
[bar] => 1794
)
[4] => stdClass Object
(
[foo] => 10486
[bar] => 1904
)
)
Now I would like to convert this structure to this:
Array
(
[0] => stdClass Object
(
[name] => 'foo'
[data] => Array (
9992, 10115, 10263, 10363, 10486
)
)
[1] => stdClass Object
(
[name] => 'bar'
[data] => Array(
1508, 1598, 1690, 1794, 1904
)
)
)
I have tried this code but it does not gave me the expected structure
$return = array();
$i = 0;
foreach($object as &$row) {
foreach( $row as $key => $val ) {
$return[$i]['name'] = $key;
// This is my custom function that does the same
// thing for objects as array_search does for arrays
$search = object_search($key, $row);
if( $search ) {
$return[$search]['data'][] = $val;
} else {
$return[$i]['data'][] = $val;
}
}
$i++;
}
return $return;
Try this
$result = array();
foreach ($array1 as $row) {
foreach ($row as $key => $value) {
$result[$key][] = $value;
}
}
$result2 = array();
foreach ($result as $key => $value) {
$obj = array();
$obj['name'] = $key;
$obj['data'] = $value;
$result2[] = $obj;
}
The code may fail, but you got the idea.
If you could give me your array in php code I can test my code again.
$c1 = new stdClass();
$c1->foo = 123;
$c1->bar = 345;
$c2 = new stdClass();
$c2->foo = 444;
$c2->bar = 555;
$arr = array();
$arr[] = $c1;
$arr[] = $c2;
$tfoo = array();
$tbar = array();
foreach($arr as $a) {
$tfoo[] = $a->foo;
$tbar[] = $a->bar;
}
$foo = array_unique($tfoo);
$bar = array_unique($tbar);
$result = array();
$result[0] = new stdClass();
$result[0]->name = "foo";
$result[0]->data = $foo;
$result[1] = new stdClass();
$result[1]->name = "bar";
$result[1]->data = $bar;
print_r($result);
Related
{"id":34,"first_name":"xus"}
{"id":34,"first_name":"xus"}
{"id":4,"first_name":"ABC"}
{"id":4,"first_name":"ABC"}
$newlist = [];
$values = [];
foreach ($appointment_list as $key => $value) {
# code...
$values[] = $value['users'];
foreach($values as $val){
$newlist[$val->id]=$values;
}
unset($newlist[$key][$values]);
}
I want to remove duplicate value from object show distinct value base on id and want to count duplicate exist of each id
Expected
id 34 has 2 duplicate
and it should return one object
{"id":34,"first_name":"xus", "count":2}
something like that
You can use array_reduce
$arr = array(
array("id" => 34,"first_name" => "xus"),
array("id" => 34,"first_name" => "xus"),
array("id" => 4,"first_name" => "ABC"),
array("id" => 4,"first_name" => "ABC"),
);
$result = array_reduce($arr, function($c, $v){
if ( !isset( $c[$v["id"]] ) ) {
$c[$v["id"]] = $v;
$c[$v["id"]]["count"] = 1;
} else {
$c[$v["id"]]["count"]++;
}
return $c;
}, array());
$result = array_values( $result );
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[id] => 34
[first_name] => xus
[count] => 2
)
[1] => Array
(
[id] => 4
[first_name] => ABC
[count] => 2
)
)
The simplest way of doing this is to create an empty array and map your objects using "id" as a key.
Here's the working snippet
<?php
$objectsRaw = [];
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
# decode the json objects into PHP arrays
$objects = array_map(
function($objectJson) {
$object = json_decode($objectJson, true);
return $object;
},
$objectsRaw
);
# map the objects
$result = [];
foreach($objects as $object) {
if (array_key_exists($object['id'], $result) === false) {
$object['count'] = 1;
$result[$object['id']] = $object;
continue;
}
$result[$object['id']]['count']++;
}
# encode result
$resultRaw = array_map('json_encode', $result);
# would look like
# Array
# (
# [34] => {"id":34,"first_name":"xus","count":2}
# [4] => {"id":4,"first_name":"ABC","count":2}
# )
# reset array keys (if you need this)
$resultRaw = array_values($resultRaw);
# would look like
# Array
# (
# [0] => {"id":34,"first_name":"xus","count":2}
# [1] => {"id":4,"first_name":"ABC","count":2}
# )
I'm trying to group airlines with relations into single chains.
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
)
[1] => Array
(
[0] => Alitalia
[1] => Lufthansa
)
[2] => Array
(
[0] => Transaero
[1] => United
)
[3] => Array
(
[0] => United
[1] => Alitalia
)
[4] => Array
(
[0] => Volotea
[1] => Iberia
)
[5] => Array
(
[0] => Transaero
[1] => Aeroflot
)
)
From that array I need to find connections between elements and combine it to groups. Expected results:
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
[3] => United
[4] => Alitalia
[5] => Lufthansa
)
[1] => Array
(
[0] => Volotea
[1] => Iberia
)
)
Can anyone help with that? I've tried a dozen of ways but still get no success.
The most closest way I've tried which works but not in all cases:
function array_searchRecursive($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && array_searchRecursive($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
foreach ($newarr as $key => $airlines)
{
foreach ($airlines as $lastkey => $airline)
{
$index = array_searchRecursive($airline,$newarr);
echo $airline.$index."\n";
if ($index !== false)
{
$newarr[$index] = array_merge($newarr[$index],$airlines);
$lastarr[] = $index;
}
}
}
But it doesn't match all values in array.
Recursive function will help you. You are welcome )
$arr = array(
array('Aeroflot','S7','Transaero'),
array('Alitalia','Lufthansa'),
array('Transaero','United'),
array('United','Alitalia'),
array('Volotea','Iberia'),
array('Transaero','Aeroflot')
);
function getConnections($arr,$curr_line_n=0,$num=0) {
for($i=0;$i<count($arr[$curr_line_n]);$i++) {
$cur_air_name = $arr[$curr_line_n][$i];
for($k=$curr_line_n+1; $k<count($arr); $k++) {
for($l=0;$l<count($arr[$k]);$l++) {
if ($arr[$k][$l]==$cur_air_name) {
$arr[$curr_line_n] = array_values(array_unique(array_merge($arr[$curr_line_n],$arr[$k])));
array_splice($arr,$k,1);
$num++;
$arr = getConnections($arr,$curr_line_n,$num);
}
}
}
}
$num++;
$curr_line_n++;
if ($curr_line_n!=count($arr)) {
$arr = getConnections($arr,$curr_line_n,$num);
}
return $arr;
}
print_r(getConnections($arr));
As per your example you are just grouping sub arrays by taking first sub array as reference. for example if you have any elements common in first sub array and in subsequent sub arrays then you combine them into one sub array.
<?php
$arr = array(
array('a', 'b', 'c', 'd'),
array('d', 't'),
array('t', 'f'),
array('k', 'o'),
array('p', 'z')
);
$arr_implode = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
$arr_implode[$key] = implode('', $value);
} else {
$arr_implode[$key] = $value;
}
}
$arr_key = array();
$result = array();
$count = count($arr_implode);
$tempj = 0;
for ($i = 0; $i <= $count; $i++) {
$flag = FALSE;
for ($j = ($i + 1); $j < $count; $j++) {
similar_text($arr_implode[$i], $arr_implode[$j], $percent);
if ($percent > 0) {
$result[] = array_merge($arr[$i],$arr[$j]);
break;
} else {
$result[] = $arr[$j];
break;
}
}
}
foreach($result as $key => $val){
$result[$key] = array_unique($val);
}
echo "<pre>";
print_r($result);
echo "</pre>";
?>
Try this code.
$arr = [
['Aeroflot', 'S7', 'Transaero'],
['Alitalia', 'Lufthansa'],
['Transaero', 'United'],
['United', 'Alitalia'],
['Volotea', 'Iberia'],
['Transaero', 'Aeroflot']
];
$hash = [];
$result = [];
foreach($arr as $set){
foreach($set as $el){
if(!$hash[$el]) $hash[$el] = [] ;
$hash[$el] = array_merge($hash[$el], $set);
}
}
function merge_connections(&$h, $key){
if(!$h[$key]) return [];
$data = [$key];
$rels = $h[$key];
unset($h[$key]);
foreach($rels as $rel){
if($rel==$key) continue;
$data = array_merge($data, merge_connections($h, $rel));
}
return $data;
}
foreach(array_keys($hash) as $company){
if(!$hash[$company]) continue;
array_push($result, merge_connections($hash, $company));
}
print_r($result);
I need to get the value from the serialized array by matching the index value.My unserialized array value is like
Array ( [info1] => test service [price_total1] => 10
[info2] => test servicing [price_total2] => 5 )
I need to display array like
Array ( [service_1] => Array ([info]=>test service [price_total] => 10 )
[service_2] => Array ([info]=>test servicing [price_total] => 5 ))
buy i get the result like the below one
Array ( [service_1] => Array ( [price_total] => 10 )
[service_2] => Array ( [price_total] => 5 ) )
my coding is
public function getServices($serviceinfo) {
$n = 1;
$m = 1;
$matches = array();
$services = array();
print_r($serviceinfo);
if ($serviceinfo) {
foreach ($serviceinfo as $key => $value) {
if (preg_match('/info(\d+)$/', $key, $matches)) {
print_r($match);
$artkey = 'service_' . $n;
$services[$artkey] = array();
$services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
$n++;
}
if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
print_r($matches);
$artkey = 'service_' . $m;
$services[$artkey] = array();
$services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
$m++;
}
}
}
if (empty($services)) {
$services['service_1'] = array();
$services['service_1']['info'] = '';
$services['service_1']['price_total'] = '';
return $services;
}
return $services;
}
I try to print the matches it will give the result as
Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 )
Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )
Thanks in advance.
try this. shorted version and don't use preg_match
function getServices($serviceinfo) {
$services = array();
if (is_array($serviceinfo) && !empty($serviceinfo)) {
foreach ($serviceinfo as $key => $value) {
if(strpos($key, 'info') === 0){
$services['service_'.substr($key, 4)]['info']=$value;
}elseif (strpos($key, 'price_total') === 0){
$services['service_'.substr($key, 11)]['price_total']=$value;
}
}
}
return $services;
}
$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);
Given the following input:
array('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11')
How can I convert it into this:
array(
'one': array(
'two': 3,
'four': array(5,6,7)
)
'eight': array(
'nine': (
'ten':11
)
}
)
$input = array ('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11');
$result = array ();
foreach ($input as $string) {
$data = array_reverse(explode('/', $string));
$tmp_array = array ();
foreach ($data as $val) {
if (empty($tmp_array)) {
$tmp_array = $val;
} else {
$tmp = $tmp_array;
$tmp_array = array ();
$tmp_array[$val] = $tmp;
}
}
$result = array_merge_recursive($result, $tmp_array);
}
echo "<pre>";
print_r($result);
echo "</pre>";
Output:
Array
(
[one] => Array
(
[two] => 3
[four] => Array
(
[0] => 5
[1] => 6
[2] => 7
)
)
[eight] => Array
(
[nine] => Array
(
[ten] => 11
)
)
)
It would be nice if we saw what you have tried.
$my_array = array('one/two/3',
'one/four/0/5',
'one/four/1/6',
'one/four/2/7',
'eight/nine/ten/11');
$result= array();
foreach ($my_array as $val) {
$ref = & $result;
foreach (explode("/", $val) as $val) {
if (!isset($ref[$val])) {
$ref[$val] = array();
}
$ref = & $ref[$val];
}
$ref = $val;
}
var_dump($result);
I have this array.
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
[isAlphaLower] =>
[isLength] =>
)
[email] => Array
(
[isEmail] => 1
)
[pPhone] => Array
(
[isPhone] =>
)
)
i want to split the array into two.
1. array with all boolean value true
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
)
[email] => Array
(
[isEmail] => 1
)
)
2. array with all boolean value false
Array
(
[name] => Array
(
[isAlphaLower] =>
[isLength] =>
)
[pPhone] => Array
(
[isPhone] =>
)
)
How do i do it?
thank you..
initialize the two new arrays
foreach the input array
foreach the inner array of each input array entry
according to the value set the one or the other of the two new arrays
done.
Example:
$arrayTrue = $arrayFalse = arrray(); # 1
foreach($arrayInput as $baseKey => $inner) # 2
foreach($inner as $key => $value) # 3
if ($value) $arrayTrue[$basekey][$key] = $value; # 4
else $arrayFalse[$basekey][$key] = $value;
function is_true($var) {
return $var;
}
function is_false($var) {
return !$var;
}
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a, 'is_true');
$result_false[$k] = array_filter($a, 'is_false');
};
or
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a);
$result_false[$k] = array_filter($a, function ($x) { return !$x; } );
};
As your array is a 2 level array, you will need to use 2 loops.
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
if ($secondLevelValue)
$trueValues[$key][$key2] = $secondLevelValue;
else
$falseValues[$key][$key2] = $secondLevelValue;
}
}
A 3 level array would be:
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
foreach($secondLevelValue AS $key3=>$thirdLevelValue) {
if ($thirdLevelValue)
$trueValues[$key][$key2][$key3] = $thirdLevelValue;
else
$falseValues[$key][$key2][$key3] = $thirdLevelValue;
}
}
}