i have an array in below format
$op = Array
(
[0] => Array
(
[0] => Array
(
[contact_id] => 36
[sender_id] => 79
[sendto] => 9192
)
[1] => Array
(
[event_id] => 145
[sender_id] => 9139
[sendto] => 9192
)
)
[1] => Array
(
[0] => Array
(
[event_id] => 145
[sender_id] => 9272
[sendto] => 9290
)
)
[2] => Array
(
[0] => Array
(
[event_id] => 145
[sender_id] => 9138
[sendto] => 9316
)
[1] => Array
(
[event_id] => 145
[sender_id] => 9283
[sendto] => 9316
)
)
)
i want to filter array in a way that resultant array's key should be different sendto values and all sender_id under that sendto shoud come under that array's key
Desired output
Array
(
[9192] => Array
(
[0] =>79
[1] =>9139
)
[9290] =>Array
(
[0]=>9272
)
[9316] =>Array
(
[0] =>9138
[1] =>9283
)
)
although i tried with below code
foreach ($op as $ok=>$ov)
{
if( array_key_exists($ov['sendto'],$mid))
$mid[$ov['sendto']][]=$ok;
else
$mid[$ov['sendto']]=$ok;
}
but this one display notice:Undefined index: sendto
please tell me where i m doing wrong?? i always stuck in such problem
Something like this:
<?php
//Test Array
$op = array(
array(
array(
'contact_id' => 36,
'sender_id' => 79,
'sendto' => 9192
),
array(
'contact_id' => 145,
'sender_id' => 9139,
'sendto' => 9192
)
),
array(
array(
'contact_id' => 145,
'sender_id' => 9272,
'sendto' => 9290
)
),
array(
array(
'contact_id' => 145,
'sender_id' => 9138,
'sendto' => 9316
),
array(
'contact_id' => 145,
'sender_id' => 9283,
'sendto' => 9316
)
),
);
//Switch array format
$new = array();
foreach($op as $element)
{
foreach($element as $entity)
{
if(!isset($new[$entity['sendto']]))
{
$new[$entity['sendto']] = array();
}
$new[$entity['sendto']][] = $entity['sender_id'];
}
}
//Debug the new array.
print_r($new);
Try:
$mid = array();
foreach($op as $tmp_array)
{
foreach($tmp_array as $message)
{
if (!isset($mid[$message['sendto']]))
$mid[$message['sendto']] = array();
$mid[$message['sendto']][] = $message['sender_id'];
}
}
You should go like this:
foreach ($op as $ok=>$ov)
{
if(!array_key_exists('sendto',$mid))
{
$mid[$ov['sendto']] = array();
}
$mid[$ov['sendto']][] = $ov['sender_id'];
}
Related
I have the following array, we'll call it $arr and I have prepared a sample array. I need to manipulate the path $arr['svg'] to have a specific key and value always at index 0 position. This is a sample data-set and depending on the data I'm working with the key's and values are not fixed, however the main point is to always have the title array (key and value) at the top of the svg array.
$arr = array("svg" =>
array(
0 => array("#style" => "overflow:visible", "#xlink:href" => "test.png"),
1 => array("g" => "", "#id" => "Layer_2"),
2 => array("g" => "", "#id" => "Layer_3"),
3 => array("title" => "test")
),
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
);
I am trying to achieve two things under the array path $arr['svg']
If the array key title exists in $arr['svg'] and it is not in index 0 position
then move it to index 0 of $arr['svg'] and shift everything else
down.
If the array key title DOES NOT exist in $arr['svg'] then add it array('title' =>
'test') to index 0 position of $arr['svg'] and shift
everything else down.
The expected output of $arr will be like so:
Array
(
[svg] => Array
(
[0] => Array
(
[title] => test
)
[1] => Array
(
[#style] => overflow:visible;
[#xlink:href] => test.png
)
[2] => Array
(
[g] =>
[#id] => Layer_2
)
[3] => Array
(
[g] =>
[#id] => Layer_3
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
I am trying to use this function to achieve this but it seems this function only works from the root array position $arr, not within a specific path $arr['svg']. If it can be modified to work within a specific path that would hopefully solve the issue.
//source: https://gist.github.com/wpscholar/0deadce1bbfa4adb4e4c
function push_at_to_associative_array($array, $key, $new ){
$keys = array_keys( $array );
$index = array_search( $key, $keys, true );
$pos = false === $index ? count( $array ) : $index + 1;
$array = array_slice($array, 0, $pos, true) + $new + array_slice($array, $pos, count($array) - 1, true);
return $array;
}
Usage:
$title = array("title" => "test');
$arr = push_at_to_associative_array($arr, 'svg', $title);
process the svg array into a new one setting [0] to the default title if we later find a title, replace svg[0]['title'] with the found one, then finally replace the original svg part of the array with the new one.
$arr = [
"svg" =>
[
["#style" => "overflow:visible", "#xlink:href" => "test.png"],
["g" => "", "#id" => "Layer_2"],
["g" => "", "#id" => "Layer_3"],
["title" => "Fred"]
],
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
];
function push_at_to_associative_array(&$arr)
{
$new_svg = [];
foreach ($arr['svg'] as $key => $svg){
if ( $key == 0){
$new_svg[] = ['title'=>'test'];
}
if ( !array_key_exists('title', $svg) ){
$new_svg[] = $svg;
} else {
# amend title
$new_svg[0]['title'] = $svg['title'];
}
}
$arr['svg'] = $new_svg;
}
push_at_to_associative_array($arr);
print_r($arr);
RESULTS
Array
(
[svg] => Array
(
[0] => Array
(
[title] => Fred
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[g] =>
[#id] => Layer_2
)
[3] => Array
(
[g] =>
[#id] => Layer_3
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
And if you run it without a title in the array
$arr = [
"svg" =>
[
["#style" => "overflow:visible", "#xlink:href" => "test.png"],
["g" => "", "#id" => "Layer_2"],
["g" => "", "#id" => "Layer_3"]
],
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
];
function push_at_to_associative_array(&$arr)
{
$new_svg = [];
foreach ($arr['svg'] as $key => $svg){
if ( $key == 0){
$new_svg[] = ['title'=>'test'];
}
if ( !array_key_exists('title', $svg) ){
$new_svg[] = $svg;
} else {
# amend title
$new_svg[0]['title'] = $svg['title'];
}
}
$arr['svg'] = $new_svg;
}
push_at_to_associative_array($arr);
print_r($arr);
RESULT
Array
(
[svg] => Array
(
[0] => Array
(
[title] => test
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[g] =>
[#id] => Layer_2
)
[3] => Array
(
[g] =>
[#id] => Layer_3
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
An easy solution would be to do something like this:
function fix_array( $array ) {
$svg_title_index = array_key_first(
array_filter(
$array['svg'],
fn($item) => isset($item['title'])
)
);
if (! $svg_title_index) {
array_unshift($array['svg'], ['title' => 'test']);
} elseif($svg_title_index > 0) {
$value = $array['svg'][$svg_title_index];
unset($array['svg'][$svg_title_index]);
array_unshift($array['svg'], $value);
}
return $array;
}
/* CASE 1 - SVG EXISTS BUT IS NOT FIRST */
$array = [
'svg' => [
[
'#style' => 'overflow:visible;',
'##xlink:href' => 'test.png'
],
[
'title' => 'some existing title',
],
],
'#version' => '1.2',
'#baseProfile' => 'tiny-ps',
'#id' => 'Layer_1',
'#xmlns' => 'http://www.w3.org/2000/svg'
];
print_r(fix_array( $array ));
/* CASE 2 - SVG DOES NOT EXIST */
$array = [
'svg' => [
[
'#style' => 'overflow:visible;',
'##xlink:href' => 'test.png'
]
],
'#version' => '1.2',
'#baseProfile' => 'tiny-ps',
'#id' => 'Layer_1',
'#xmlns' => 'http://www.w3.org/2000/svg'
];
print_r(fix_array( $array ));
You can see it in action here
Ok so OP want's to move the array with the title attribute to the start of the array or insert a test value if it doesn't exist.
The below function should achieve this. It might not be the most beautiful or effient but it should put you on the right track.
function order_svg_title( array $input, ?string $default_title ) {
$position = null;
// Find position of existing title (if exists).
foreach( $input[ 'svg' ] as $key => $value ) {
if ( isset( $value[ 'title' ] ) && $key !== 0 ) {
$position = $key;
}
}
// Doesn't already exist, add default title (if not null).
if ( is_null( $position ) ) {
array_unshift( $input[ 'svg' ], array( 'title' => $default_title ) );
}
// Title exists but it's in the wrong position.
else {
$value = $input[ 'svg' ][ $position ];
unset( $input[ 'svg' ][ $position ] );
array_unshift( $input[ 'svg' ], $value );
}
return $input;
}
So for this example usage would be...
$arr = array(
"svg" => array(
array(
"#style" => "overflow:visible",
"#xlink:href" => "test.png"
),
array(
array("g" => "", "#id" => "Layer_2"),
array("g" => "", "#id" => "Layer_3")
)
),
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
);
$new_arr = order_svg_title( $arr, 'test' );
Would return:
Array
(
[svg] => Array
(
[0] => Array
(
[title] => test
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[0] => Array
(
[g] =>
[#id] => Layer_2
)
[1] => Array
(
[g] =>
[#id] => Layer_3
)
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
Now with an existing title:
$arr = array(
"svg" => array(
array(
"#style" => "overflow:visible",
"#xlink:href" => "test.png"
),
array(
array("g" => "", "#id" => "Layer_2"),
array("g" => "", "#id" => "Layer_3")
),
array(
"title" => "In the wrong position. I should be moved."
)
),
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
);
$new_arr = order_svg_title( $arr, 'test' );
Would return:
Array
(
[svg] => Array
(
[0] => Array
(
[title] => In the wrong position. I should be moved.
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[0] => Array
(
[g] =>
[#id] => Layer_2
)
[1] => Array
(
[g] =>
[#id] => Layer_3
)
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
I need to convert the below 2d array in to specified 2d array format. Array contains multiple parent and multiple child array. Also, have tried to convert the code, but am not getting the expected output.
This is the code what i have tried,
$a1 = array(
'0' =>
array(
'banner_details' =>
array(
'id' => 2,
'section_id' => 24
),
'slide_details' =>
array(
0 => array(
'id' => 74,
'name' => 'Ads1'
),
1 => array(
'id' => 2,
'name' => 'Ads2'
)
)
),
'1' =>
array(
'banner_details' =>
array(
'id' => 106,
'section_id' => 92
),
'slide_details' =>
array(
0 => array(
'id' => 2001,
'name' => 'Adv1'
),
1 => array(
'id' => 2002,
'name' => 'Adv2'
)
)
)
);
$s = [];
for($i = 0; $i<2; $i++) {
foreach($a1[$i]['slide_details'] as $vs){
$s[] = $vs;
}
}
My output:
Array
(
[0] => Array
(
[id] => 74
[name] => Ads1
)
[1] => Array
(
[id] => 2
[name] => Ads2
)
[2] => Array
(
[id] => 2001
[name] => Adv1
)
[3] => Array
(
[id] => 2002
[name] => Adv2
)
)
Expected output:
Array
(
[24] => Array
(
[0] => 74
[1] => 2
)
[92] => Array
(
[0] => 2001
[1] => 2002
)
)
please check the above code and let me know.
Thanks,
You can apply next simple foreach loop with help of isset() function:
foreach($a1 as $data){
if (isset($data['banner_details']['section_id'])){
$s[$data['banner_details']['section_id']] = [];
if (isset($data['slide_details'])){
foreach($data['slide_details'] as $row){
$s[$data['banner_details']['section_id']][] = $row['id'];
}
}
}
}
Demo
If you know that indexes like banner_details or slide_details or section_id will be there always then you can skip isset() in if statements.
You can use array_column function for simple solution:
$result = [];
foreach ($a1 as $item)
{
$result[$item['banner_details']['section_id']] = array_column($item['slide_details'], 'id');
}
var_dump($result);
I need to create an XML-RPC server that gets cities with their corresponding IDs. What I do as a response is looking weird to me because of unnecessary duplicate entries but I couldnt find a better way.
Array
(
[cityID] => Array
(
[0] => 34
[1] => 35
[2] => 06
)
[cityName] => Array
(
[0] => Istanbul
[1] => Izmir
[2] => Ankara
)
)
I implemented above response. With this implementation:
$response = array(
array(
'cityID' => array(array('34', '35', '06'), 'array'),
'cityName' => array(array('Istanbul', 'Izmir', 'Ankara'), 'array')
),
'struct'
);
The problem is I want to take a response like this :
Array
(
[cities] => Array
(
['34'] => 'Istanbul'
['35'] => 'Izmir'
['06'] => 'Ankara'
)
)
So I tried to implement it like this :
$response = array(
array(
'cities' => array(array('34'=>'Istanbul', '35'=>'Izmir', '06'=>'Ankara'), 'array')
),
'struct'
);
But it fails with this implementation. What am I doing wrong ?
Thanks
You have array like following
$response = array ( 'cityID' => array (
0 => 34,
1 => 35,
2 => 06
),
'cityName' => array(
0 => 'Istanbul',
1 => 'Izmir',
2 => 'Ankara'
)
);
$newarray = array();
foreach($response['cityID'] as $key => $cityid){
$newarray['cities'][$cityid] = $response['cityName'][$key];
}
print_r($newarray);
You will be getting the expected array.
Array
(
[cities] => Array
(
[34] => Istanbul
[35] => Izmir
[6] => Ankara
)
)
This is how I do it, in Code Igniter 3
$array = array ( 'cityID' => array (
0 => 34,
1 => 35,
2 => 06
),
'cityName' => array(
0 => 'Istanbul',
1 => 'Izmir',
2 => 'Ankara'
)
);
foreach($array['cityID'] as $key => $cityid){
$response[] = array(array(
$cityid => array($array['cityName'][$key],'string'),
),'struct');
}
return $this->xmlrpc->send_response(array($response,'array'));
This is my array:
Array ( [0] => Array ( [license_id] => 172 [valid_from] => 2014-10-13 14:39:32 [valid_till] => 2020-10-22 00:00:00 [us_user_user_id] => 810 [us_group_group_id] => [li_voucher_voucher_id] => 90128 [pr_product_product_ids] => 91,92,93 [li_license_setting_license_setting_id] => 55 [li_voucher_setting_voucher_setting_id] => 222 [product_data] => {"answer_layer":true} ) [1] => Array ( [license_id] => 173 [valid_from] => 2014-10-13 14:39:48 [valid_till] => 2020-10-21 14:39:48 [us_user_user_id] => 810 [us_group_group_id] => [li_voucher_voucher_id] => 90129 [pr_product_product_ids] => 94 [li_license_setting_license_setting_id] => 73 [li_voucher_setting_voucher_setting_id] => 223 [product_data] => {"answer_layer":true} ) [2] => Array ( [license_id] => 371 [valid_from] => 2015-01-07 12:05:36 [valid_till] => 2021-01-15 12:05:36 [us_user_user_id] => 810 [us_group_group_id] => [li_voucher_voucher_id] => 89008 [pr_product_product_ids] => 173 [li_license_setting_license_setting_id] => 56 [li_voucher_setting_voucher_setting_id] => 160 [product_data] => {"answer_layer":true} ) [3] => Array ( [license_id] => 441 [valid_from] => 2015-03-04 16:10:18 [valid_till] => 2016-03-03 16:10:18 [us_user_user_id] => 810 [us_group_group_id] => [li_voucher_voucher_id] => 124457 [pr_product_product_ids] => 243 [li_license_setting_license_setting_id] => 201 [li_voucher_setting_voucher_setting_id] => 315 [product_data] => ) )
I want to filter the the value [valid_till] where the value from [license_id] = 441.
I already filtered the specific license with license_id 441 with the next code:
$filtered = array_filter($userlicenses, function($v) { return $v['license_id'] == '441'; });
But this gives me the complete array. I want only the [valid_till] where [license_id] = 441.
array_reduce is an easy way to just return the value:
$result = array_reduce($userlicenses,
function($c, $v) {
return $v['license_id'] == '441' ? $v['valid_till'] : false;
}
);
And an array_column method:
$result = array_column($userlicenses, 'valid_from', 'license_id')[441];
"Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved." function.array-filter
This means your variable $filtered is an array again/still.
If it's only one dimensional (i.e. you have always exactly one result) you can simply access the key valid_till of the first element returned this way:
<?php
$userlicenses = array(
0 => array (
'license_id' => 172,
'valid_from' => '2014-10-13 14:39:32',
'valid_till' => '2020-10-22 00:00:00'
),
1 => array (
'license_id' => 173,
'valid_from' => '2014-10-13 14:39:48',
'valid_till' => '2020-10-21 14:39:48'
),
2 => array (
'license_id' => 371,
'valid_from' => '2015-01-07 12:05:36',
'valid_till' => '2021-01-15 12:05:36'
),
3 => array (
'license_id' => 441,
'valid_from' => '2015-03-04 16:10:18',
'valid_till' => '2016-03-03 16:10:18'
)
);
$filtered = array_filter($userlicenses, function($v) { return $v['license_id'] == '441'; });
var_dump( $filtered );
if( is_array( $filtered ) )
{
$first_el = reset( $filtered );
$valid_till = $first_el['valid_till'];
var_dump( $valid_till );
}
?>
How can we find the count of duplicate elements in a multidimensional array and concat of ids ?
I have an array of skill names with feed ids. I need to count skill name and concat of feed ids.
Array
(
[0] => Array
(
[skill_name] => PHP
[feed_id] => 100
)
[1] => Array
(
[skill_name] => CSS
[feed_id] => 105
)
[2] => Array
(
[skill_name] => Php
[feed_id] => 110
)
[3] => Array
(
[skill_name] => Php
[feed_id] => 111
)
[4] => Array
(
[skill_name] => CSS
[feed_id] => 112
)
[5] => Array
(
[skill_name] => Javascript
[feed_id] =>114
)
}
Output should be like below.
Array
(
[0] => Array
(
[skill_name] => PHP
[feed_id] => 100, 110, 111
[count]=>3
)
[1] => Array
(
[skill_name] => CSS
[feed_id] => 105, 112
[count]=>2
)
[2] => Array
(
[skill_name] => Javascript
[feed_id] => 114
[count]=>1
)
}
Thanks in advance!!
//Assumption: Input is in $in
//Step 1: Cumulate
$tmp=array();
foreach ($in as $skill) {
if (isset($tmp[$skill['skill_name']]))
$tmp[$skill['skill_name']][]=$skill['feed_id'];
else
$tmp[$skill['skill_name']]=array($skill['feed_id']);
}
//Step 2: Fix up desired output format
$out=array();
foreach ($tmp as $k=>$v)
$out[]=array(
'skill_name' => $k,
'feed_id' => implode(', ', $v),
'count' => sizeof($v)
);
//Result is in $out
This is perfectly achievable with a single loop using temporary keys and simple concatenation and incrementation.
Code: (Demo)
$array = [
['skill_name' => 'PHP', 'feed_id' => 100],
['skill_name' => 'CSS', 'feed_id' => 105],
['skill_name' => 'Php', 'feed_id' => 110],
['skill_name' => 'Php', 'feed_id' => 111],
['skill_name' => 'CSS', 'feed_id' => 112],
['skill_name' => 'Javascript', 'feed_id' => 114]
];
foreach ($array as $row) {
$upperSkill = strtoupper($row['skill_name']);
if (!isset($result[$upperSkill])) {
$result[$upperSkill] = $row + ['count' => 1]; // plus acts as array_merge here
} else {
$result[$upperSkill]['feed_id'] .= ",{$row['feed_id']}"; // concatenate
++$result[$upperSkill]['count']; // increment
}
}
var_export(array_values($result)); // reindex and display
Output:
array (
0 =>
array (
'skill_name' => 'PHP',
'feed_id' => '100,110,111',
'count' => 3,
),
1 =>
array (
'skill_name' => 'CSS',
'feed_id' => '105,112',
'count' => 2,
),
2 =>
array (
'skill_name' => 'Javascript',
'feed_id' => 114,
'count' => 1,
),
)