How to combine same name with its value in array - php

hi I have array like this
Array
(
[0] => stdClass Object
(
[name] => text_input
[value] => kalpit
)
[1] => stdClass Object
(
[name] => wpc_chkbox[]
[value] => Option two
)
[2] => stdClass Object
(
[name] => wpc_chkboxasdf[]
[value] => Option one
)
[3] => stdClass Object
(
[name] => wpc_chkboxasdf[]
[value] => Option two
)
[4] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 1
)
[5] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 2
)
[6] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 3
)
[7] => stdClass Object
(
[name] => wpc_radios
[value] => Option one
)
)
now my question is how to combine same name value in onc place, here in above array I have wpc_inline_checkbox[] is repeating 3 times so I want to make it .. I can use array_uniqe() but I want value of other duplicate index...
[4] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 1,2,3
)
can anyone help me to solve this
Thanks in advance

This is assuming both name/value are strings
<?php
$objects; // This is your array
$sorted = array(); // This is the sorted array
// Loop over your array
foreach($objects as $object)
{
// Check if object exists in sorted array
if( array_key_exists($object->name, $sorted) )
{
// Object with this name is already in sorted array simply add to it
$obj = $sorted[$object->name];
// Update the values
$obj->value = $obj->value . ',' . $object->value;
} else {
// Object is not in the sorted array add it now
$sorted[$object->name] = $object;
}
}
?>

Sorry, your case is not ordinary, so you will need to do it by hand
$properArray = array();
foreach ($originArray as $value) {
if ( ! isset($properArray[$value['name']])) {
$properArray[$value['name']] = array(
'name' = $value['name'],
'value' = ''
);
}
if (isset($properArray[$value['name']]['value'])) {
$properArray[$value['name']]['value'] = $properArray[$value['name']]['value'] . ',' .$value['value']; //better to use array in this place
} else {
$properArray[$value['name']]['value'] = $value['value']
}
}
$originArray = array_values($properArray);
regards,

You have an array of object. You will have to loop through and assign them. Something like
$newArray = [];
foreach ($array as $obj) {
if (!isset($newArray[$obj->name])) {
$newArray[$obj->name] = $obj;
} else {
$newArray[$obj->name]->value .= ",{$obj->value}";
}
}
The new array should look like
["wpc_inline_chkbox[]"] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => "1,2,3"
)
But you should change [value] from string to array.

## Use this ##
$arr = array(
array(
'name' => 'hi'
,'value' => 1
)
,array(
'name' => 'hi'
,'value' => 2
)
, array(
'name' => 'hi2'
,'value' => 1
)
, array(
'name' => 'hi4'
,'value' => 1
)
,array(
'name' => 'hi0'
,'value' => 4
)
, array(
'name' => 'hi0'
,'value' => 3
)
, array(
'name' => 'hi1'
,'value' => 10
)
);
print_r($arr);
$arrTracker = array();
for ($i=0; $i <sizeof($arr) ;$i++) {
for($j = $i+1; $j<sizeof($arr);$j++){
if($arr[$i]['name'] == $arr[$j]['name']){
$arr[$i]['value'] .= ','.$arr[$j]['value'];
$arrTracker[$j] = $j;
}
}
}
// if you want to unset duplicate name and corresponding value, use below forloop, otherwise it's unnecessary
foreach($arrTracker as $tracker){
unset($arr[$tracker]);
}
$arr = array_values($arr);
print_r($arr);

Related

PHP - How To Grouping if value same in array

This my array example
Array
(
[0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [0] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) ) [count] => 1 )
[1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 1 )
[2] => Array ( [_id] => 5f76d2488ee23083d3cd1a4a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 1)
)
And i want to group if product value same, like this,
Array
(
[0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [0] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) ) [count] => 1 )
[1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 2 )
)
It makes no sense to retain the first level ids since you are arbitrarily trashing some of the first level ids (damaging the relationships) during the merging process.
Instead I recommend that you only isolate the data that is accurately related.
If this output does not serve your needs, then I'll ask for further question clarification.
By assigning temporary keys to your output array, the output array also acts as a lookup array by which you can swiftly check for uniqueness. The "null coalescing operator" (??) sets a fallback value of 0 when an id is encountered for the first time -- this prevents generating any warnings regarding undeclared keys.
Code: (Demo)
$array = [
['_id' => '5f76b1788ee23077dccd1a2c', 'product' => ['_id'=>'5d0391a4a72ffe76b8fcc610'], 'count'=> 1],
['_id' => '5f76b6288ee2300700cd1a3a', 'product' => ['_id'=>'5d0391b6a72ffe76b8fcc611'], 'count'=> 1],
['_id' => '5f76d2488ee23083d3cd1a4a', 'product' => ['_id'=>'5d0391b6a72ffe76b8fcc611'], 'count'=> 1]
];
$productCounts = [];
foreach ($array as $item) {
$productId = $item['product']['_id'];
$productCounts[$productId] = ($productCounts[$productId] ?? 0) + $item['count'];
}
var_export($productCounts);
Output:
array (
'5d0391a4a72ffe76b8fcc610' => 1,
'5d0391b6a72ffe76b8fcc611' => 2,
)
If you insist of the desired output in your question, then it can be as simple and efficient as this...
Code: (Demo)
$result = [];
foreach ($array as $item) {
$productId = $item['product']['_id'];
if (!isset($result[$productId])) {
$result[$productId] = $item;
} else {
$result[$productId]['count'] += $item['count'];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'_id' => '5f76b1788ee23077dccd1a2c',
'product' =>
array (
'_id' => '5d0391a4a72ffe76b8fcc610',
),
'count' => 1,
),
1 =>
array (
'_id' => '5f76b6288ee2300700cd1a3a',
'product' =>
array (
'_id' => '5d0391b6a72ffe76b8fcc611',
),
'count' => 2,
),
)
You can try the below code it will work for you :-)
<?php
$Myarray = array(['_id'=> '5f76b1788ee23077dccd1a2c', 'product'=> ['_id'=>'5d0391a4a72ffe76b8fcc610'] ,'count'=> 1 ],
['_id'=> '5f76b6288ee2300700cd1a3a', 'product'=> ['_id'=>'5d0391b6a72ffe76b8fcc611'] ,'count'=> 1 ],
['_id'=> '5f76d2488ee23083d3cd1a4a', 'product'=> ['_id'=>'5d0391b6a72ffe76b8fcc611'] ,'count'=> 1 ]
);
$user_array = [];
$temp_array = [];
foreach($Myarray as $temp)
{
$found = array_search($temp['product']['_id'], $temp_array);
if($found !== false)
{
$i = 0;
foreach($user_array as $temp1)
{
if($temp1['product']['_id'] == $temp['product']['_id'])
{
$sum = $temp1['count'] + 1;
$user_array[$i]['count'] = $sum;
}
$i++;
}
}
else
{
array_push($user_array,$temp);
array_push($temp_array,$temp['product']['_id']);
}
}
print_r($user_array);
?>
This will produce below Output
Array ( [0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) [count] => 1 ) [1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) [count] => 2 ) )

Get value from array using key

I have an array like this:
Array
(
[0] => Array
(
[settingID] => 1
[name] => audioCueDistance
[setValue] => false
)
[1] => Array
(
[settingID] => 2
[name] => audioCueDistanceToGo
[setValue] => true
)
[2] => Array
(
[settingID] => 3
[name] => audioCues
[setValue] => true
)
[3] => Array
(
[settingID] => 4
[name] => audioCueStyle
[setValue] => default
)
[4] => Array
(
[settingID] => 5
[name] => audioCueTime
[setValue] => true
)
[5] => Array
(
[settingID] => 6
[name] => isMetric
[setValue] => true
)
How can I get individual values from key for example, I would like to output the setValue of isMetric.
Thanks
foreach ($foo as $bar) {
if ($bar['name'] == "isMetric") {
// Use setValue here
}
}
From what I understand you want to do something like $myArray['isMetric']['setValue'].
As your array is not in that form you need to map it that way.
$myArray = array(
array(
'settingID'=>6,
'name'=>'isMetric',
'value'=>true
)
);
$myAssocArray = array_reduce($myArray, function($carry, $item){
$carry[$item['name']] = $item;
return $carry;
}, array());
echo $myAssocArray['isMetric']['setValue'];
Run this code here: https://repl.it/CZ3R
foreach($array as $element)
{
if($element['name'] = 'isMetric')
return $element['setValue'];
}
throw new \Exception('isMetric Not Found.');

Move value to next element of array

See the attached example that i use to build my array
foreach($something AS $key => $row)
{
$output[] = array("name"=>$row["name"], "points"=>$row["points"]);
}
print_r($output);
Here's the output:
Array
(
[0] => Array
(
[name] => Mark
[points] => 1
)
[1] => Array
(
[name] => Sara
[points] => 2
)
[2] => Array
(
[name] => Jack
[points] => 3
)
)
What i'm trying to do is moving $row["points"] to next array element to get this output:
Array
(
[0] => Array
(
[name] => Mark
[points] =>
)
[1] => Array
(
[name] => Sara
[points] => 1
)
[2] => Array
(
[name] => Jack
[points] => 2
)
)
I don't care if there's some data loss or if my [points] => 3 goes in a new array. I just have to programmatically move $row["points"] always to next element. I'm playing with next() function with no success and also with $key+1 which i'm sure i can't use to achieve the result.
Is it possible to make it on top while i'm building the array or am i forced to move the element later with a separate function? In other words what would you do?
Try This:
$output = array();
$something = array(
'0' => array(
'name' => 'Mark',
'points' => 1,
),
'1' => array(
'name' => 'Sara',
'points' => 2,
),
'2' => array(
'name' => 'Jack',
'points' => 3,
)
);
$point = '';
foreach($something AS $key => $row)
{
$output[$key] = array("name"=>$row["name"], "points"=>$point);
$point = $row['points'];
}
echo '<pre>';
print_r($output);
Try if it helps:
foreach($something AS $key => $row)
{
$output[$key]['name'] = $row["name"];
$output[$key+1]['points'] = $row["points"];
}
print_r($output);
Use:
foreach($array as $key => $each)
{
$array[0]['points'] = "";
$array[$key]['name'] = $each["name"];
if(isset($array[$key+1])) $array[$key+1]['points'] = $each["points"];
}
print_r($array);

how can i count an element if it appears more than once in the same array?

how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);

Build an array out of another with a different structure

I have this array as follow:
Array (
[pageid_01_page_name] => first Page
[pageid_01_Style] => full
[thePageID_1] => pageid_01
[theElementID_1] => 1
[source_type_1] => slideshow_box
[pageid_01_1_slideshow_box] => Array ( [layout] => one
[content_id] => Array ( [0] => 856 )
[slideshow_timeout] => 8
[slideshow_height] => 400
[image_resize] => on
[image_crop] => on
[list_orderby] => date
[list_order] => DESC
[slideshow_buttons] => on )
[thePageID_2] => pageid_01
[theElementID_2] => 2
[source_type_2] => banner_box
[pageid_01_2_banner_box] => Array ( [layout] => one
[text] => test
[button_text] => Button Text
[button_link] => a link )
)
I need to build another array out of the one above, with this structure:
Array (
[pages] => Array ( [pageid_01] => stdClass Object
( [pageName] => first Page
[style] => full
[pageID] => pageid_001
[contents] => Array (
[2] => stdClass Object (
[element_id] => 1
[content_type] => slideshow_box
[layout] => one
[content_id] => Array ( [0] => 856 )
[slideshow_timeout] => 8
[slideshow_height] => 400
[image_resize] => on
[image_crop] => on
[list_orderby] => date
[list_order] => DESC
[slideshow_buttons] => on
)
[3] => stdClass Object (
[element_id] => 2
[content_type] => banner_box
[layout] => one
[text] => test
[button_text] =>Button text
[button_link] => a link
)
)
Updated with more details:
The way i'm building the second array right now is like this:
$pages = new \stdClass();
$i=0;
$page=0;
$thepagename = '_page_name';
if(isset($thepagename))
{
if(in_array($thepagename, $AllPages))
{ foreach($AllPages as $k => $v) {
$page = str_replace('_page_name','',$k);
#$pages->pages[$page]->pageID = $page;
#$pages->pages[$page]->pageName = $v;
if(stristr($k, 'theElementID_') == true) {
$element_id = $v;
}
if(stristr($k, '_slideshow_box') == true) {
$i++;
#$pages->pages[$page]->contents[$i]->element_id = $element_id;
$pages->pages[$page]->contents[$i]->content_type = 'slideshow_box';
$pages->pages[$page]->contents[$i]->layout = $v["layout"];
$pages->pages[$page]->contents[$i]->content_id = #$v["content_id"];
$pages->pages[$page]->contents[$i]->slideshow_timeout = $v["slideshow_timeout"];
$pages->pages[$page]->contents[$i]->slideshow_height = $v["slideshow_height"];
$pages->pages[$page]->contents[$i]->image_resize = $v["image_resize"];
$pages->pages[$page]->contents[$i]->image_crop = $v["image_crop"];
$pages->pages[$page]->contents[$i]->list_orderby = $v["slideshow_orderby"];
$pages->pages[$page]->contents[$i]->list_order = $v["slideshow_order"];
$pages->pages[$page]->contents[$i]->slideshow_buttons = $v["slideshow_buttons"];
}
}
}
}
and so on....
but this way takes a lot of coding while the contents can be much much more...
First of all,you can loop your array, get all values and keys, The second,built another array, push all key and values into the new array. just like
$new_array = ($new_array,values1,values2,.......);
hope it can help you

Categories