How add a link on comma separated multidimensional array - php

How add a link using the id on comma separated multidimensional array?
What I done so far:
$string = implode(", ", array_column($title_genres, "name"));
echo $string;
My array:
array(4) {
[0]=>
object(stdClass)#66 (3) {
["id"]=>
string(2) "21"
["name"]=>
string(8) "Aventure"
["tmdb_id"]=>
string(2) "12"
}
[1]=>
object(stdClass)#67 (3) {
["id"]=>
string(2) "20"
["name"]=>
string(9) "Animation"
["tmdb_id"]=>
string(2) "16"
}
[2]=>
object(stdClass)#63 (3) {
["id"]=>
string(1) "8"
["name"]=>
string(8) "Familial"
["tmdb_id"]=>
string(5) "10751"
}
[3]=>
object(stdClass)#70 (3) {
["id"]=>
string(1) "9"
["name"]=>
string(11) "Fantastique"
["tmdb_id"]=>
string(2) "14"
}
}

I'd suggest a simple foreach on $title_genres to build a new array of just linked names, then you can do the implode on that to output with commas:
$links = array();
foreach($title_genres as $item) {
$links[] = ''. $item['name'] .'';
}
echo implode(', ',$links);
Update 1: In case you are using stdClass objects:
$links = array();
foreach($title_genres as $item) {
$links[] = ''. $item->name .'';
}
echo implode(', ',$links);
Update 2: An all in one line mash using array_map ;)
echo implode(', ', array_map(function($a){
return ''. $a->name .'';
},$title_genres) );

Here's the array_map solution, you decide if you consider it simpler than foreach.
$string = implode(",", array_map(function($item) {
return "<a href='/some.php?id={$item->id'}'>{$item->name}</a>";
}, $title_genres));
echo $string;
If the base URL is in a variable, you can access it using a use() declaration.
$baseurl = base_url();
$string = implode(",", array_map(function($item) use ($baseurl) {
return "<a href='$baseurl/some.php?id={$item->id'}'>{$item->name}</a>";
}, $title_genres));

Related

search multi-dimentional array for matching elements

I have a multi dimensional array. I need to search through the arrays and retrieve instance of dates that match each other.
This is my array:
$dateArray = array(8) {
[0]=>
array(15) {
["bookable_id"]=>
string(1) "1"
["event_date"]=>
string(10) "2019-09-11"
}
[1]=>
array(15) {
["bookable_id"]=>
string(1) "1"
["event_date"]=>
string(10) "2019-09-11"
}
[2]=>
array(15) {
["bookable_id"]=>
string(1) "4"
["event_date"]=>
string(10) "2019-10-17"
}
[3]=>
array(15) {
["bookable_id"]=>
string(1) "4"
["event_date"]=>
string(10) "2019-10-17"
}
[4]=>
array(15) {
["bookable_id"]=>
string(1) "3"
["event_date"]=>
string(10) "2020-09-15"
}
[5]=>
array(15) {
["bookable_id"]=>
string(1) "3"
["event_date"]=>
string(10) "2020-09-15"
}
[6]=>
array(15) {
["bookable_id"]=>
string(1) "2"
["event_date"]=>
string(10) "2021-09-09"
}
}
This is my function:
function searchMatchingDates($compare, $array)
{
foreach ($array as $val) {
if ($compare["event_date"]== $val["event_date"]){
return $val;
}
}
return null;
And this is how i searched it:
foreach ($dateArray as $compare) {
$match = searchMatchingDates($compare, $array);
}
if($match){
echo "$compare['bookable_id'] + $match['bookable_id']; "
}
This works and return the date. It however return duplicate dates as the array will compare twice.
I need a way to remove an array once an array has been compared once .
For example, once array once has ran its iteration it needs to be removed so that the next array does not do a comparison on it.
If I understand the question, you want to return the dates which feature more than once in the array?
You could do this by counting all of those which feature more than once (array_count_values() https://www.php.net/manual/en/function.array-count-values.php combined with array_column()), then filtering the array based on that outcome.
// get dates which feature more than once
$dateCounts = array_filter(
array_count_values(array_column($dateArray, 'event_date')),
function ($count) {
return $count > 1;
}
);
// filter those matching dates
$matching = array_filter($dateArray, function ($date) use ($dateCounts) {
return isset($dateCounts[$date['event_date']]);
});
var_dump($matching);

PHP: Combining data with a shared key from a single array into new array

I have this array:
array(5) {
[0]=>
array(4) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTextSeq"]=>
string(1) "1"
["productTxtVal"]=>
string(5) "Text1"
}
[1]=>
array(4) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTextSeq"]=>
string(1) "2"
["productTxtVal"]=>
string(5) "Text2"
}
[2]=>
array(4) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTextSeq"]=>
string(1) "3"
["productTxtVal"]=>
string(5) "Text3"
}
[3]=>
array(4) {
["productCode"]=>
string(4) "X002"
["productUPC"]=>
string(3) "262"
["productTextSeq"]=>
string(1) "1"
["productTxtVal"]=>
string(5) "Text1"
}
[4]=>
array(4) {
["productCode"]=>
string(4) "X002"
["productUPC"]=>
string(3) "262"
["productTextSeq"]=>
string(1) "2"
["productTxtVal"]=>
string(5) "Text2"
}
}
With the above input, I want the output array to look like this:
array(2) {
[0]=>
array(3) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTxtVal"]=>
string(17) "Text1 Text2 Text3"
}
[1]=>
array(3) {
["productCode"]=>
string(4) "X002"
["productUPC"]=>
string(3) "262"
["productTxtVal"]=>
string(11) "Text1 Text2"
}
}
The resulting array does not need the productTextSeq key, just the combined values of productTextVal, when the productCode is the same. I've searched SO for examples of this but it seems every example I've found are based on multiple input arrays. I know I can brute force this with nested foreach functions but would love a more elegant solution.
I ended up just doing it the brute force method, here is my solution if anyone's interested:
$productData = array();
$sortedData = array();
$comments = '';
$saveKey = '';
$appendComment = false;
$idx = 0;
foreach ($data as $key=>$value) {
foreach ($value as $k=>$v) {
if ($k == 'productCode') {
if ($v == $saveKey) {
$appendComment = true;
} else {
$appendComment = false;
$saveKey = $v;
if ($idx !== 0) { // Don't write to array on first iteration!
$productData['productTxtVal'] = $comments;
$sortedData[] = $productData;
}
}
}
if ($k == 'productTxtVal') {
if ($appendComment == true) {
$comments .= ' ' . trim($v);
} else {
$comments = trim($v);
}
}
}
$productData = $value;
$idx++;
}
Not "elegant" but it works. I also have a check after this logic in case only one productCode is in the original array, as it won't be written to the $sortedData array since the key never changes.
The following code assumes you control the contents of the original data array (due to risk of injection using extract() function) and that no 2 items with the same productCode have the same productTextSeq.
$products = [];
foreach ($data as $item) {
// extract contents of item array into variables
extract($item);
if (!isset($products[$productCode])) {
// create product array with code, upc, text as array
$products[$productCode] = compact('productCode', 'productUPC') + ['productTxtVal' => []];
}
// add text value to array with sequence as index
$products[$productCode]['productTxtVal'][$productTextSeq] = $productTxtVal;
}
$products = array_values( // ignore array keys
array_map(function($product) {
ksort($product['productTxtVal']); // sort text as array by index/ sequence
$product['productTxtVal'] = implode(' ', $product['productTxtVal']); // implode into string
return $product;
}, $products)
);
You can run the code here: https://repl.it/BWQL

Multidimensional array search using another element value

I have a multi dimensional array built dynamically.
Is it possible to get the value of an element by using another element.
e.g : search with idQ = 26 and get in return value its neighbor element values like :: idA=>49 and A=>500-10000
[0]=>
array(5) {
["idQA"]=>
string(3) "194"
["idQ"]=>
string(2) "26"
["Q"]=>
string(58) "Imposition supérieur
à 2500€ d’impôts annuel"
["idA"]=>
string(2) "49"
["A"]=>
string(10) "5000-10000"
}
[1]=>
array(5) {
["idQA"]=>
string(3) "173"
["idQ"]=>
string(2) "22"
["Q"]=>
string(20) "Si oui, laquelle(s):"
["idA"]=>
string(2) "32"
["A"]=>
string(7) "Voiture"
}
Example array :: https://gist.github.com/anonymous/9234703
Yes, like:
$founded = 0;
foreach($my_array[1] as $key => $val) {
if ($val == "something_to_search") {
$founded = $key;
break;
}
}
$before = $my_array[1][$founded-1];
$after = $my_array[1][$founded+1];

Add Array Column to Multidimensional Array Using array_merge in foreach Loop

I'm trying to add another column of data to each row in a foreach loop. It's purpose is to remember the element of data importeded from XML processed to an multidimensional array. It's stuck as a scalar though the var_dumps looks fine.
<?php
$KEY = 0;
foreach ($eventsArray as $keyMe){
$thisKey['KEY'][0] = strval($KEY);
$keyedArray = array_merge($keyMe, $thisKey);
$KEY++;
}
// Prep for multisort
foreach ($keyedArray as $key => $value){
$date[$key] = $value['DATE'];
$title[$key] = $value['TITLE'];
$link[$key] = $value['LINK'];
$slide[$key] = $value['SLIDE'];
$location[$key] = $value['LOCATION'];
$time[$key]= $value['TIME'];
$KEY[$key] = $value['KEY']; // Warning: Cannot use a scalar value as an array
}
/* var_dump(
array(7) {
["DATE"]=> array(1) { [0]=> string(10) "2012-12-18" }
["TITLE"]=> array(1) { [0]=> string(20) "Event Title" }
["LINK"]=> array(1) { [0]=> string(38) "aLinkLocation.htm" }
["SLIDE"]=> array(1) { [0]=> string(2) "16" }
["LOCATION"]=> array(1) { [0]=> string(8) "Location of Event" }
["TIME"]=> array(1) { [0]=> string(3) "8am" }
["KEY"]=> array(1) { [0]=> string(2) "23" }
}
*/

How to loop through a mulitdimensional array in php?

array(2) {
["names"]=> array(4) {
[0]=> string(4) "Edit"
[1]=> string(6) "Delete"
[2]=> string(8) "Activate"
[3]=> string(10) "Deactivate"
}
["action"]=> array(4) {
[0]=> string(4) "ajax"
[1]=> string(4) "abc"
[2]=> string(4) "def"
[3]=> string(4) "xyz"
}
}
How do i loop through this in a single foreach loop?
Assuming both arrays are of the same size and have the same keys:
foreach($array['names'] as $k => $name) {
$action = $array['actions'][$k];
// do whatever you want to do with $name and $action
}
$newArr = array();
foreach($data['names'] as $i => $val) {
$newArr[$val] = $data['actions'][$i];
}
Or if you want a one liner at that
$newArr = array_combine($data['names'], $data['action']);
I guess the best way is a recursive function which can move through even three dimensions and more
function MoveThroughArray($arr)
{
foreach($arr as $value)
{
if(is_array($value))
MoveThroughArray($value);
else
// Do Something
}
}

Categories