Sort and merge in a array - php

I have trouble in handle array PHP, I have an array:
[0] {
'email' => 'test#gmail.com',
'meta' => {
'product' => {
'id' => '1',
'content' => 'This is content'
}
}
}
[1] {
'email' => 'test2#gmail.com',
'meta' => {
'product' => {
'id' => '2',
'content' => 'This is content'
}
}
}
[2] {
'email' => 'test2#gmail.com',
'meta' => {
'product' => {
'id' => '3',
'content' => 'This is content'
}
}
}
I need to merge this array by value 'email', like this:
[0] {
'email' => 'test#gmail.com',
'meta' => {
'product' => {
'id' => '1',
'content' => 'This is content'
}
}
}
[1] {
'email' => 'test2#gmail.com',
'meta' => {
'product' => [0] {
'id' => '2',
'content' => 'This is content'
}
[1] {
'id' => '3',
'content' => 'This is content'
}
}
}
Could somebody help me?

$sorted_array = [];
$emails = [];
$i = 0;
foreach ($arr as $array) {
if(!empty($array['email']) && !empty($array['meta']['product'])){
if( in_array($array['email'], $emails)){
$i--;
} else {
$emails[] = $array['email'];
}
$sorted_array[$i]['email'] = $array['email'];
$sorted_array[$i]['meta']['product'][] = $array['meta']['product'];
$i++;
}
}
echo "<pre>";
print_r($sorted_array);
Hope this will help you

Php has many function to sort an Array. You can consult the documentation to choice the better algorithms to your case http://php.net/manual/en/array.sorting.php. And you can merge result Arrays with array_merge function, like it:
array_merge($a1,$a2)
I created an example for your code here:
http://codepad.org/zzkndGQZ

You can use the email like array's key, to end, use array_combine to have indeces since 0 to N number...
<?php
$oldArray = array(
array(
'email' => 'test#gmail.com',
'meta' => array(
'product' => array(
'id' => '1',
'content' => 'This is content'
)
)
), array(
'email' => 'test2#gmail.com',
'meta' => array(
'product' => array(
'id' => '2',
'content' => 'This is content'
)
)
), array(
'email' => 'test2#gmail.com',
'meta' => array(
'product' => array(
'id' => '3',
'content' => 'This is content'
)
)
)
);
$newArray = array();
foreach($oldArray as $element){
if(isset($newArray[$element['email']])) {
if(!isset($newArray[$element['email']]['meta']['product'][0]))
$newArray[$element['email']]['meta']['product'] = array($newArray[$element['email']]['meta']['product']);
$newArray[$element['email']]['meta']['product'][] = $element['meta']['product'];
} else {
$newArray[$element['email']] = $element;
}
}
//For index since 0 to n
print_r(array_combine(range(0,count($newArray)-1), $newArray));

You can build a new array with the sorted informations.
It should be working with something like this, but not tested:
$sorted_array = [];
$i = 0;
foreach ($unsorted_array as $array) {
if(!empty($array['email']) && !empty($array['meta']['product'])){
$sorted_array[$i]['email'] = $array['email'];
$sorted_array[$i]['meta']['product'][] = $array['meta']['product'];
$i++;
}
}
print_r($sorted_array);

Related

Search for an array value with keys from another array

I have two arrays with nearly the same structure.
The first array is $_POST data while the second one holds regex rules and some other stuff for data validation.
Example:
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
)
);
$structure = array(
'address' => array(
'city' => array(
'regex' => 'someregex'
)
)
);
Now I want to check
$data['address']['city'] with $structure['address']['city']['regex']
or
$data['foo']['bar']['baz']['xyz'] with $structure['foo']['bar']['baz']['xyz']['regex']
Any ideas how to achieve this with a PHP function?
Edit: It seems that I found a solution by myself.
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
),
'mail' => 'test#test.tld'
);
$structure = array(
'address' => array(
'city' => array(
'regex' => 'some_city_regex1',
)
),
'mail' => array(
'regex' => 'some_mail_regex1',
)
);
function getRegex($data, $structure)
{
$return = false;
foreach ($data as $key => $value) {
if (empty($structure[$key])) {
continue;
}
if (is_array($value) && is_array($structure[$key])) {
getRegex($value, $structure[$key]);
}
else {
if (! empty($structure[$key]['regex'])) {
echo sprintf('Key "%s" with value "%s" will be checked with regex "%s"', $key, $value, $structure[$key]['regex']) . '<br>';
}
}
}
return $return;
}
getRegex($data, $structure);
Given these arrays:
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
),
'foo' => array(
'bar' => array(
'baz' => array(
'xyz' => 'hij'
)
)
)
);
$structure = array(
'address' => array(
'city' => array(
'regex' => '[a-Z]'
)
),
'foo' => array(
'bar' => array(
'baz' => array(
'xyz' => array(
'regex' => '[0-9]+'
)
)
)
)
);
and this function:
function validate ($data, $structure, &$validated) {
if (is_array($data)) {
foreach ($data as $key => &$value) {
if (
array_key_exists($key, $structure)
and is_array($structure[$key])
) {
if (array_key_exists('regex', $structure[$key])) {
if (!preg_match($structure[$key]['regex'])) {
$validated = false;
}
}
validate($value, $structure[$key], $validated);
}
}
}
}
you can check the arrays against each other and get a validation result like so:
$validated = true;
validate($data, $structure, $validated);
if ($validated) {
echo 'everything validates!';
}
else {
echo 'validation error';
}
Ah, you've found a solution. Very nice.

Change Array Value

I have simple questions, How to change text if id = cur_three from array below ?
$arr = array(
'id' => 'curr',
'lists' => array(
array(
'id' => 'cur_one',
'text' => 'Dollar',
),
array(
'id' => 'cur_two',
'text' => 'Euro',
),
array(
'id' => 'cur_three',
'text' => 'Peso',
),
)
);
Thank you very much...
Something simple:
foreach($arr['lists'] as $subArr) {
if ($subArr['id'] == 'cur_three') {
$subArr['text'] = 'not Peso';
}
}
Sure. Like this:
foreach($arr['lists'] as $key => $child) {
if($child['id'] == 'cur_three') {
$arr['lists'][$key]['text'] = "INR";
}
}

Check if exists the same value in multidimensional array PHP

Let's say i have an array like this:
$array = array(
0 =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
1=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
21 =>
array(
'value' => 'adresa#gmail.com' ,
'name' => 'name1`' ),
23 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
24 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
26 =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
27 =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);
I want to know if exists duplicated value in array with key 'value' I know how to do this if i want a specified value but general no. The result must be an array with no duplicated values(eg:
$array = array(
0 =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
1=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
23 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
26 =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
27 =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);`
Please help me.
This is my try
function has_dupes($array){
$dupe_array = array();
foreach($array as $val){
if(++$dupe_array[$val] > 1){
return true;
}
}
return false;
}
Try this way:
$array = array(
'0' =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
'1'=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
'21' =>
array(
'value' => 'adresa#gmail.com' ,
'name' => 'name1`' ),
'23' =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
'24' =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
'26' =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
'27' =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);
$array = array_map("unserialize", array_unique(array_map("serialize", $array)));
$result = array_unique($array);
print_r($result);
And if you want to store all unique data in one array do it like this:
//declare $array
$unique_array = array();
foreach ($array as $key => $type) {
foreach($type as $vale => $name) {
if ($vale == 'value') {
//echo $name . '<br>';
array_push($unique_array, $name);
}
}
}
$result = array_unique($unique_array);
foreach ($result as $res) {
echo $res . '<br>';
}
Try this
$values = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($values as $key => $value)
{
if ( is_array($value) )
{
$values[$key] = $value;
}
}
print_r($values);
$unique_data = array(); // the result array
$duplicate_data = array();
$seen = array();
foreach ($array as $key => $arr) {
$value = $arr['value'];
if (!isset($seen[$value])) {
$seen[$value] = '';
$unique_data[$key] = $arr;
} else {
$duplicate_data[$key] = $arr; // optional
}
}
unset($seen); // optional in function scope

Recursive get path from multidimensional php array

I have array:
$adm_menu_old = array (
array(
'id' => 1,
'name' => 'Test1',
),
array(
'id' => 3,
'name' => 'Test3',
'childrens' => array(
array(
'id' => 31,
'name' => 'Test31',
),
array(
'id' => 32,
'name' => 'Test32',
'childrens' => array(
array(
'id' => 321,
'name' => 'Test321',
),
),
)
),
array(
'id' => 4,
'name' => 'Test4',
),
);
Say i know id value.
I need get path with all parents of this id.
For example i need get path to this element: id=321
i need get array with key name values:
array('Test3','Test32','Test321')
how should look like recursive function?
Try this function:
function getNames($id, $arr) {
$result = array();
foreach($arr as $key => $val) {
if(is_array($val)) {
if($val["id"] == $id) {
$result[] = $val["name"];
} elseif(!empty($val["childrens"]) && is_array($val["childrens"])) {
$sub_res = getNames($id, $val["childrens"]);
if(count($sub_res) > 0) {
$result[] = $val["name"];
$result = array_merge($result, $sub_res);
}
}
}
}
return $result;
}

how to get the value of my var, which double dollar var is set from multidimensional array?

i managed to dynamically create my arrays (as $$myGenre contains each name => id), but $myGenre does not contain anything... how can i make this work : $myGenre should contain every $$myGenre, $$myGenre should have its content as name => id, and we should keep each $myGenre separated from one another (here, because of the foreach, we're overriding $myGenre for each different genre) :
<?php function findSection() {
global $post, $custom_meta_fields, $myGenre;
foreach ($custom_meta_fields as $fields) {
foreach ($fields as $field) {
if ($field == $fields['genre']) {
$myGenre = array($field['title']);
$$myGenre = array();
} else {
${$myGenre}[$field['name']] = $field['id'];
}
}
var_dump($$myGenre);
}
}
$custom_meta_fields = array(
array( //THRILLER
'genre' => array( 'title' => 'Thriller'),
'fields' => array(
'name' => 'Movie1',
'desc' => 'Desc movie1',
'id' => 'id1',
'type' => 'text'),
array(
'name' => 'Movie2',
'desc' => 'desc movie2',
'id' => 'id2',
'type' => 'text'
),
array(
'name' => 'movie3',
'desc' => 'desc',
'id' => 'id3',
'type' => 'image'
)
),
array(
'genre' => array( 'title' => 'Action'),
'fields' => array('name' => 'Action1',
'desc' => 'desc act1',
'id' => 'idAction1')
)
);
findSection();
Thanks for your help
I modified your code so that it uses associative arrays, since you were doing pretty weird things with your double dollars.
<?php
function findSection() {
global $post, $custom_meta_fields, $myGenre;
foreach ($custom_meta_fields as $fields) {
foreach ($fields as $field) {
if ($field == $fields['genre']) {
$genre =$field['title'];
$all[$genre]= array();
} else {
$all[$genre][$field['name']] = $field['id'];
}
}
}
echo "<pre>".var_export($all,TRUE)."</pre>";
}
Result:
array (
'Thriller' =>
array (
'Movie1' => 'id1',
'Movie2' => 'id2',
'movie3' => 'id3',
),
'Action' =>
array (
'Action1' => 'idAction1',
),
)

Categories