Search through an array with two values - php

Good day,
I'm trying to search through an array.
I have two IDs (productId, secondaryProductId) in an array ($package) with some other data:
array (size=7)
'title' => string 'Compleet' (length=8)
'productId' => string '102' (length=5)
'price' => string '45.75' (length=5)
'secondaryProductId' => string '150' (length=5)
'secondaryPrice' => string '58.75' (length=5)
I have an array with arrays ($availableProducts):
array (size=2)
0 =>
array (size=3)
'product_id' => int 102
'description' => string 'some description for 102'
'order_link' => string 'some/link/102'
1 =>
array (size=3)
'product_id' => int 150
'description' => string 'some description for 150'
'order_link' => string 'some/link/150'
2 =>
array (size=3)
'product_id' => int 160
'description' => string 'some description for 160'
'order_link' => string 'some/link/160'
3 =>
array (size=3)
'product_id' => int 140
'description' => string 'some description for 140'
'order_link' => string 'some/link/140'
What I want to achieve is to search both product IDs in the $availableProducts array.
If they exists (like 102 and 150 with there description and link exist) I want the description and link to be set in the first array where both the product IDs are.
Like this:
array (size=7)
'title' => string 'Complete' (length=8)
'productId' => string '102' (length=5)
'price' => string '45.75' (length=5)
'secondaryProductId' => string '150'
'secondaryPrice' => string '58.75'
'description' => string 'some description for 102'
'order_link' => string 'link/for/102'
'secondaryDescription' => string 'some description for 150'
'secondaryOrder_link' => string 'some/link/150'
If one of them doesn't exist I want it's ID and price to either be removed or set as an empty string (doesn't matter).
Like this:
array (size=7)
'title' => string 'Complete' (length=8)
'productId' => string '102' (length=5)
'price' => string '45.75' (length=5)
'secondaryProductId' => string ''
'secondaryPrice' => string ''
'description' => string 'some description for 102'
'order_link' => string 'link/for/102'
What I have tried so far with a foreach loop:
$finalArray = array();
foreach ($availableProducts as $product) {
if ($package['productId'] == $product->product_id) {
$package['orderLink'] = $product->order_link;
$finalArray[] = $package;
}
if ($package['secondaryProductId'] == $product->product_id) {
$package['secondaryOrderLink'] = $product->order_link;
$finalArray[] = $package;
}
}
But it doesn't work. At first it looks fine to set the orderLink, but then it kind of runs double:
array (size=2)
0 =>
array (size=5)
'productId' => string '102' (length=5)
'price' => string '35.75' (length=5)
'secondaryProductId' => string '150' (length=5)
'secondaryPrice' => string '48.75' (length=5)
'orderLink' => string 'link/for/102'
1 =>
array (size=6)
'productId' => string '102' (length=5)
'price' => string '35.75' (length=5)
'secondaryProductId' => string '150' (length=5)
'secondaryPrice' => string '48.75' (length=5)
'orderLink' => string 'link/for/102'
'secondaryOrderLink' => string 'link/for/150'
I've tried playing around a bit, also tried in_array. But I clearly do something wrong. Any help will be highly appreciated.

Here you go (truncated version)
$availableProducts = [
0 => [
'product_id' => 102,
'description' => 'some description for 102',
'order_link' => 'some/link/102',
], 1 => [
'product_id' => 150,
'description' => 'some description for 150',
'order_link' => 'some/link/150'
], 2 => [
'product_id' => 160,
'description' => 'some description for 160',
'order_link' => 'some/link/160'
]
];
$array1 = [
'title' => 'Compleet',
'productId' => '102',
'price' => '45.75',
'secondaryProductId' => '150',
'secondaryPrice' => '58.75',
];
print_r(
array_intersect_key(
array_column($availableProducts, null, 'product_id'),
array_flip([$array1['productId'], $array1['secondaryProductId']])
)
);
Output
Array
(
[102] => Array
(
[product_id] => 102
[description] => some description for 102
[order_link] => some/link/102
)
[150] => Array
(
[product_id] => 150
[description] => some description for 150
[order_link] => some/link/150
)
)
Sandbox
note - this only works if product_id is unique in $availableProducts
Basically array_column($availableProducts, null, 'product_id') will restructure your array using product_id as the key (no duplicate ids), then you can get the intersection between this and an array with the 2 id's you need to find. I filped it because I am to lazy to make them as keys, which they need to be for array_intersect_key (obviously) to work.
array_column - is extremely powerful for array to array comparison. There are several neat tricks you can do with it...
The above shows you how to filter out only the 2 you want, But if you just want to update the original array ($array1 in this example) is a simple matter of doing this:
$res = array_column($availableProducts, null, 'product_id');
$array1['productId'] = $res[$array1['productId']]['description'];
$array1['secondaryProductId'] = $res[$array1['secondaryProductId']]['description'];
Output
Array
(
[title] => Compleet
[productId] => some description for 102
[price] => 45.75
[secondaryProductId] => some description for 150
[secondaryPrice] => 58.75
)
Sandbox
See with the product ID's as the keys (see output from example one) we can just use the value to get that segment of the multi-dimensional array by it's product_id - directly.
Obviously it's pretty easy to do this too now
$res = array_column($availableProducts, null, 'product_id');
$array1['productId'] =['description' => $res[$array1['productId']]['description'], 'order_link' => $res[$array1['productId']]['order_link']];
$array1['secondaryProductId'] =['description' => $res[$array1['secondaryProductId']]['description'], 'order_link' => $res[$array1['secondaryProductId']]['order_link']];
Output:
Array
(
[title] => Compleet
[productId] => Array
(
[description] => some description for 102
[order_link] => some/link/102
)
[price] => 45.75
[secondaryProductId] => Array
(
[description] => some description for 150
[order_link] => some/link/150
)
[secondaryPrice] => 58.75
)
I'm not sure what you want as the end result, but maybe this will help you.
Enjoy

Related

Remove array entry with one or more duplicate values in multidimensional array

How can I remove an array entry with one or more duplicate values in multidimensional array? For example if I have:
array (size=4)
0 =>
array (size=3)
'food' => string 'bread' (length=5)
'color' => string 'white' (length=5)
'language' => string 'php' (length=3)
1 =>
array (size=3)
'food' => string 'rice' (length=4)
'color' => string 'purple' (length=6)
'language' => string 'c#' (length=2)
2 =>
array (size=3)
'food' => string 'pasta' (length=5)
'color' => string 'red' (length=3)
'language' => string 'php' (length=3)
3 =>
array (size=3)
'food' => string 'steak' (length=5)
'color' => string 'yellow' (length=6)
'language' => string 'ruby' (length=4)
Since there is a php entry in array[2], I want to delete the entire record so that I can have
array (size=4)
0 =>
array (size=3)
'food' => string 'bread' (length=5)
'color' => string 'white' (length=5)
'language' => string 'php' (length=3)
1 =>
array (size=3)
'food' => string 'rice' (length=4)
'color' => string 'purple' (length=6)
'language' => string 'c#' (length=2)
2 =>
array (size=3)
'food' => string 'steak' (length=5)
'color' => string 'yellow' (length=6)
'language' => string 'ruby' (length=4)
I have tried this code:
array_map("unserialize", array_unique(array_map("serialize", $array)));
and it doesn't work. What am I doing wrong?
Since your objects are all different (for instance, they all have different colors), array_unique will not reduce the number of elements.
Instead, key your array elements by their language property: that will eliminate duplicate php entries, and then convert that associated array back to an indexed one:
foreach($array as $row) {
$result[$row['language']] = $row;
}
$result = array_values($result);
The solution using array_intersect and array_merge functions (will cover duplicates for all keys):
$arr = [
['food' => 'bread', 'color' => 'white', 'language' => 'php'],
['food' => 'rice', 'color' => 'purple', 'language' => 'c#'],
['food' => 'pasta', 'color' => 'red', 'language' => 'php'],
['food' => 'steak', 'color' => 'yellow', 'language' => 'ruby']
];
$values = []; // auxiliary array
foreach ($arr as $k => $a) {
if (array_intersect($values, $a)){
unset($arr[$k]); // removing the whole `entry` if it contains duplicates in any key
} else {
$values = array_merge($values, array_values($a));
}
}
print_r($arr);
The output:
Array
(
[0] => Array
(
[food] => bread
[color] => white
[language] => php
)
[1] => Array
(
[food] => rice
[color] => purple
[language] => c#
)
[3] => Array
(
[food] => steak
[color] => yellow
[language] => ruby
)
)

Symfony2 Doctrine Array of joined objects

I have the following repository:
class CustomerRepository extends EntityRepository
{
public function searchCustomer($criteria)
{
$q = $this->createQueryBuilder('c');
$q->join('TeamERPCustomerBundle:Company', 'o',
'WITH', 'c.company = o.id');
if (isset($criteria) and $criteria!=""){
$q->orWhere(sprintf("c.customer_name like '%s'", '%'.$criteria.'%'));
(...)
}
$q = $q->getQuery()->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
return $q;
}
}
I call it from the controller as follows:
$result = $this->getDoctrine()->getManager()
->getRepository('TeamERPCustomerBundle:Customer')
->searchCustomer($customerInfo);
It returns an array of elements as follows:
array (size=20)
0 =>
array (size=9)
'id' => int 1
'customer_name' => string 'Abel' (length=4)
'address' => string 'Calle 52 # 60, % 3era y G. Quezada, Nuevo Sosa' (length=46)
'postal_address' => string '75100' (length=5)
'city_town_village' => string 'Las Tunas' (length=9)
'e_mail' => string 'abel#ltu.sld.cu' (length=15)
'land_line' => string '346386' (length=6)
'cell_phone' => null
'fax' => null
1 =>
array (size=2)
'id' => int 1
'company_name' => string 'Debswana' (length=8)
2 =>
array (size=9)
'id' => int 2
'customer_name' => string 'Kay' (length=3)
'address' => null
'postal_address' => null
'city_town_village' => null
'e_mail' => null
'land_line' => null
'cell_phone' => null
'fax' => null
3 =>
array (size=2)
'id' => int 3
'company_name' => string 'DTC' (length=3)
(...)
It gives one element of the array per object, but what I want it the classic mysql join; as result an array of elements of the same type. Something like mergin elements 1 and 2 together.
The other problem with this query is that is does not work like that classic join ether, it gives all the customers, but only the companies that are not repeated.
Can anyone help me to get a uniform array of elements?
Edit: I managed to find a solution:
$em = $this->getEntityManager();
$query = $em->createQuery('
SELECT c, i
FROM TeamERPCustomerBundle:Customer c
JOIN c.company i');
//$query->setParameter('id', '1'); With this is can add as many parameter as I need
return $query->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
This returned something like this:
array (size=11)
0 =>
array (size=10)
'id' => int 1
'customer_name' => string 'Abel' (length=4)
'address' => string 'Calle 52 # 60, % 3era y G. Quezada, Nuevo Sosa' (length=46)
'postal_address' => string '75100' (length=5)
'city_town_village' => string 'Las Tunas' (length=9)
'e_mail' => string 'abel#ltu.sld.cu' (length=15)
'land_line' => string '346386' (length=6)
'cell_phone' => null
'fax' => null
'company' =>
array (size=2)
'id' => int 1
'company_name' => string 'Debswana' (length=8)
As you might have already appreciated this array is different from what I was getting before. so now I just have to go through the array and change it to what ever I want. for instance:
foreach ($result as $key => $value){
$result[$key]['company'] = $value['company']['company_name'];
}
Now we are talking. This Is kind of what I wanted:
array (size=11)
0 =>
array (size=10)
'id' => int 1
'customer_name' => string 'Abel' (length=4)
'address' => string 'Calle 52 # 60, % 3era y G. Quezada, Nuevo Sosa' (length=46)
'postal_address' => string '75100' (length=5)
'city_town_village' => string 'Las Tunas' (length=9)
'e_mail' => string 'abel#ltu.sld.cu' (length=15)
'land_line' => string '346386' (length=6)
'cell_phone' => null
'fax' => null
'company' => string 'Debswana' (length=8)

How can I get tweets from new twitter api 1.1?

I have just implemented https://github.com/thujohn/twitter-l4 for Laravel 4, it basically pulls in an array
of tweets from a search of a hashtag.
It seems like its working, I think there are some things that are not working though.
I get a blank screen with no errors which means a positive sign.
Here is my code.
PHP:
$tweets = Twitter::getSearch(array('q' => 'secretsocial', 'count' => 100, 'format' => 'array'));
var_dump($tweets);
This code basically gives me an array of json:
array (size=2)
'statuses' =>
array (size=20)
0 =>
array (size=24)
'metadata' =>
array (size=2)
'result_type' => string 'recent' (length=6)
'iso_language_code' => string 'en' (length=2)
'created_at' => string 'Fri May 16 14:28:14 +0000 2014' (length=30)
'id' => int 467310562603331586
'id_str' => string '467310562603331586' (length=18)
'text' => string 'On that #merch #grind. #spotify #swag just got shipped in. #secretsocial #free #leeds #leedsuniā€¦ http://t.co/67phqjeg5W' (length=121)
'source' => string 'Instagram' (length=59)
'truncated' => boolean false
'in_reply_to_status_id' => null
'in_reply_to_status_id_str' => null
'in_reply_to_user_id' => null
'in_reply_to_user_id_str' => null
'in_reply_to_screen_name' => null
'user' =>
array (size=40)
'id' => int 167993141
'id_str' => string '167993141' (length=9)
'name' => string 'Maral Erol' (length=10)
'screen_name' => string 'liaaca' (length=6)
'location' => string 'Leeds / San Diego' (length=17)
'description' => string 'Music/Culture/Entertainment Enthusiast.' (length=39)
'url' => string 'http://t.co/FL3uuA6QcN' (length=22)
'entities' =>
array (size=2)
'url' =>
array (size=1)
'urls' =>
array (size=1)
0 =>
array (size=4)
'url' => string 'http://t.co/FL3uuA6QcN' (length=22)
'expanded_url' => string 'http://linkd.in/R70tjB' (length=22)
'display_url' => string 'linkd.in/R70tjB' (length=15)
'indices' =>
array (size=2)
0 => int 0
1 => int 22
'description' =>
array (size=1)
'urls' =>
array (size=0)
empty
So from that I wrote this:
if(isset($tweets->statuses) && is_array($tweets->statuses)) {
if(count($tweets->statuses)) {
foreach($tweets->statuses as $tweet) {
echo $tweet->text;
}
}
else {
echo 'The result is empty';
}
}
I get no errors on the page. Can anyone point me in the right direction please?
Cheers
Since each $tweet is an array so you should use $tweet['text'] instead of $tweet->text
foreach($tweets->statuses as $tweet) {
echo $tweet['text'];
}
Also $tweets->statuses should be $tweets['statuses'].

PHP rebuild a big array

array (size=10)
'image' =>
array (size=3)
0 => string 'BlackLingerie(42).jpg' (length=21)
1 => string 'BlackLingerie(43).jpg' (length=21)
2 => string 'BlackLingerie(44).jpg' (length=21)
'text' =>
array (size=3)
0 => string '' (length=0)
1 => string '' (length=0)
2 => string '' (length=0)
'author' =>
array (size=3)
0 => string '' (length=0)
1 => string '' (length=0)
2 => string '' (length=0)
'date' =>
array (size=3)
0 => string '' (length=0)
1 => string '' (length=0)
2 => string '' (length=0)
'verImage' =>
array (size=3)
0 => string 'upload' (length=6)
1 => string 'upload' (length=6)
2 => string 'upload' (length=6)
'imagePicsPath' =>
array (size=3)
0 => string 'http://127.0.0.1/develop/mvc/public/images/pics/BlackLingerie(42).jpg'/' (length=77)
1 => string 'http://127.0.0.1/develop/mvc/public/images/pics/BlackLingerie(43).jpg'/' (length=77)
2 => string 'http://127.0.0.1/develop/mvc/public/images/pics/BlackLingerie(44).jpg'/' (length=77)
'imageThumbPath' =>
array (size=3)
0 => string 'http://127.0.0.1/develop/mvc/public/images/thumbs/BlackLingerie(42).jpg'/' (length=79)
1 => string 'http://127.0.0.1/develop/mvc/public/images/thumbs/BlackLingerie(43).jpg'/' (length=79)
2 => string 'http://127.0.0.1/develop/mvc/public/images/thumbs/BlackLingerie(44).jpg'/' (length=79)
'imagePath' =>
array (size=3)
0 => string 'http://127.0.0.1/develop/mvc/public/images/pics/BlackLingerie(42).jpg'/' (length=77)
1 => string 'http://127.0.0.1/develop/mvc/public/images/pics/BlackLingerie(43).jpg'/' (length=77)
2 => string 'http://127.0.0.1/develop/mvc/public/images/pics/BlackLingerie(44).jpg'/' (length=77)
'imageID' =>
array (size=3)
0 => string '0' (length=1)
1 => string '1' (length=1)
2 => string '2' (length=1)
'submitUploadImages' => string 'Ladda upp bilder till databas' (length=29)
Want to rebuild this array to an more useful array. Like this
array
( [image0] (
'name' =>
'text' =>
'author' =>
'date' =>
'verImage' =>
'imagePicsPath' =>
'imageThumbPath' =>
'imagePath' =>
'imageID' =>
)
[image1] (
'name' =>
'text' =>
'author' =>
'date' =>
'verImage' =>
'imagePicsPath' =>
'imageThumbPath' =>
'imagePath' =>
'imageID' =>
)
And so on depending on how many pictures there is, the keys inside the image array holds the values for each image. Like name, path so on. The incoming array is a $_POST that holds multiple form input data. Need some help to crack this one guys. Need to iterate trough the $_POST array, get the contents and transform to a new array ?
I want unique image arrays that holds the image information before doing my stuff with the database =)
I haven't tested this but it should work:
$incomingArray = $_POST['array'];
$sortedArray = array();
for($i = 0; $i < count($incomingArray); $i++){
foreach($incomingArray as $key => $value){
$sortedArray["image".$i][$key] = $value[i];
}
}
Doing it this way means you don't have to write $sortedArray["image".$i]['NAME'] = $incomingArray['NAME'][$i] for each image value (name, test, author etc.).
Try
foreach( $array as $1st_level_key => $1st_level_value ) {
foreach ( $1st_level_value as $2nd_level_key => $2nd_level_value ) {
$new_array['image'.$2nd_level_key][$1st_level_key] = $2nd_level_value;
}
}
Short answer yes, pretty much like this:
for($i = 0; $i < count($YourArray); $i++)
{
$NewArray["image".$i]["name"] = $YourArray["name"][$i];
...
}

need to sort the entire array by title Doctrine 2

I am using Doctrine 2, here when I am getting array like below.
I have to sort the entire by "title" it has levels for brand name, model name, engine capacity, I need to sort all the title's
$repo = $em->getRepository ( 'Teon_Model_Folder' );
$tree = $repo->childrenHierarchy ();
I am getting result like this, I need to sort by title in every level
array
0 =>
array
'id' => int 28
'title' => string 'BMW' (length=3)
'slug' => string 'bmw' (length=3)
'flags' => null
'lft' => int 2
'lvl' => int 1
'rgt' => int 105
'root' => int 25
'__children' =>
array
0 =>
array
'id' => int 128
'title' => string '3-series' (length=3)
'flags' => null
'lvl' => int 2
......
1 =>
array
...
2 =>
array
...
3 =>
array
...
4 =>
array
...
5 =>
array
...
1 =>
array
'id' => int 46
'title' => string 'Ford' (length=4)
'slug' => string 'ford' (length=4)
'flags' => null
'lft' => int 106
'lvl' => int 1
'rgt' => int 113
'root' => int 25
'__children' =>
array
0 =>
array
...
2 =>
array
'id' => int 56
'title' => string 'Honda' (length=5)
'slug' => string 'honda' (length=5)
'flags' => null
'lft' => int 114
'lvl' => int 1
'rgt' => int 123
'root' => int 25
'__children' =>
array
0 =>
array
...
Check out
Sort array by key
This should sort array by key - in your case key is title.

Categories