If elseif condition inside foreach with array - php

I'm using a if elseif condition inside the foreach loop. Inside both if and elseif two different functions are calling and retrieving value to same array $nice[]. If I run the following code, only the if condition is working.
$youtube = array(
'https://www.youtube.com/watch?v=nCwRJUg3tcQ1&list=PLv5BUbwWA5RYaM6E-QiE8WxoKwyBnozV2&index=4',
'http://vimeo.com/channels/vimeogirls/87973054123',
'http://www.youtube.com/watch?v=nCwRJUg3tcQ2&feature=relate',
'http://youtube.com/v/nCwRJUg3tcQ3?feature=youtube_gdata_player');
$nice = array();
foreach ($youtube as $url) {
if(preg_grep("/youtu/i", $youtube)){
$nice[] = getYoutubeId($url);
}elseif(preg_grep("/vimeo/i", $youtube)){
$nice[] = getVimeoId($url);
}
}
print_r($nice);
function getVimeoId($url)
{
if (preg_match('#(?:https?://)?(?:www.)?(?:player.)?vimeo.com/(?:[a-z]*/)*([0-9]{6,11})[?]?.*#', $url, $m)) {
return 'v_'.$m[1];
}
return false;
}
function getYoutubeId($url)
{
$parts = parse_url($url);
if (isset($parts['host'])) {
$host = $parts['host'];
if (false === strpos($host, 'youtube') &&
false === strpos($host, 'youtu.be')
)
{
return false;
}
}
if (isset($parts['query'])) {
parse_str($parts['query'], $qs);
if (isset($qs['v'])) {
return 'y_'.$qs['v'];
}
else if (isset($qs['vi'])) {
return 'y_'.$qs['vi'];
}
}
if (isset($parts['path'])) {
$path = explode('/', trim($parts['path'], '/'));
return 'y_'.$path[count($path) - 1];
}
return false;
}
The current output is:
Array (
[0] => y_nCwRJUg3tcQ1
[1] =>
[2] => y_nCwRJUg3tcQ2
[3] => y_nCwRJUg3tcQ3
)
There is no value in [1] position.

First-off, your if() Clause is checking on the main array$youtube instead of the value: $url.Perhaps, the snippet below helps:
$youtube = array(
'https://www.youtube.com/watch?v=nCwRJUg3tcQ1&list=PLv5BUbwWA5RYaM6E-QiE8WxoKwyBnozV2&index=4',
'http://vimeo.com/channels/vimeogirls/87973054123',
'http://www.youtube.com/watch?v=nCwRJUg3tcQ2&feature=relate',
'http://youtube.com/v/nCwRJUg3tcQ3?feature=youtube_gdata_player');
$nice = array();
foreach ($youtube as $url) {
if(preg_match("#youtu#i", $url)){
$nice[] = getYoutubeId($url);
}elseif(preg_match("#vimeo#i", $url)){
$nice[] = getVimeoId($url);
}
}

Related

Search inside multidimensional array and return other key value

I have the following
Multidimensional array.
What I'm trying to do is to search for an IDITEM value and if it's found, return the value of the "PRECO" key.
I'm using the following function to check if the value exists and it works fine, but I can't find a way to get the "PRECO" value of the found IDITEM.
Function:
function search_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && search_array($needle, $element))
return true;
}
return false;
}
Anyone can help me with that?
You can change the first if statement to return it instead of returning a boolean :
function search_array($needle, $haystack) {
if(in_array($needle, $haystack) && array_key_exists('PRECO', $haystack)) {
return $haystack['PRECO'];
}
foreach($haystack as $element) {
if(is_array($element))
{
$result = search_array($needle, $element);
if($result !== false)
return $result;
}
}
return false;
}
The easiest idea I can remember is converting that boolean search_array into a path creator, where it will return the path for the item, or false if it isn't found.
function get_array_path_to_needle($needle, array $haystack)
{
if(in_array($needle, $haystack))
{
return true;
}
foreach($haystack as $key => $element)
{
if(is_array($element) && ($path = get_array_path_to_needle($needle, $element)) !== false)
{
return $path === true ? $key : $key . '.' . $path;
}
}
return false;
}
Then, since you already have the path, then rerun the array to fetch the item
function get_array_value_from_path(array $path, array $haystack)
{
$current = $haystack;
foreach($path as $key)
{
if(is_array($current) && array_key_exists($key, $current))
{
$current = $current[$key];
}
else
{
return false;
}
}
return $current;
}
This wont get you the PRECO, but it will return the item (array) where id found the value you searched for.
So a simple usage would be:
$path = get_array_path_to_needle('000000000000001650', $data);
$item = get_array_value_from_path(explode('.', $path), $data);
// here you have full array for that item found
print_r($item);
// here you have your price
print_r($item['PRECO']);
Use a static variable to remember the status between multiple function calls, and also to store the desired PRECO value. It makes the function remember the value of the given variable ($needle_value in this example) between multiple calls.
So your search_array() function should be like this:
function search_array($needle, $haystack){
static $needle_value = null;
if($needle_value != null){
return $needle_value;
}
foreach($haystack as $key => $value){
if(is_array($value)){
search_array($needle, $value);
}else if($needle == $value){
$needle_value = $haystack['PRECO'];
break;
}
}
return $needle_value;
}
This function will finally return $needle_value, which is your desired PRECO value from the haystack.
The simplest way is to use a foreach loop twice. Check for the key and store the result into an array for later use.
Based on your array, the below
$search = '000000000000001650';
foreach($array as $element){
foreach ($element['ITEM'] as $item){
if (isset($item['IDITEM']) and $item['IDITEM'] == $search){
$results[] = $item['PRECO'];
}
}
}
print_r($results);
Will output
Array
(
[0] => 375
)
Here is the simple example with array:
// your array with two indexes
$yourArr = array(
0=>array(
'IDDEPARTAMENTO'=>'0000000001',
'DESCRDEPT'=>'Área',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001367',
'DESCRITEM'=>'PISTA TESTE DRIV',
'PRECO'=>'1338.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001925',
'DESCRITEM'=>'PISTA TESTE DRIV2',
'PRECO'=>'916'),
)
),
1=>array(
'IDDEPARTAMENTO'=>'0000000010',
'DESCRDEPT'=>'Merch',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000002036',
'DESCRITEM'=>'PISTA TESTE DRIV23',
'PRECO'=>'200.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001608',
'DESCRITEM'=>'PISTA CRACHÁ DRIV4',
'PRECO'=>'44341'),
)
));
// solution
$newArr = array();
foreach ($yourArr as $value) {
foreach ($value as $key => $innerVal) {
if($key == 'ITEM'){
foreach ($innerVal as $key_inner => $keyinner) {
if(!empty($keyinner['IDITEM'])){
$newArr[$keyinner['IDITEM']] = $keyinner['PRECO'];
}
}
}
}
}
echo "<pre>";
print_r($newArr);
Result values with IDITEM:
Array
(
[000000000000001367] => 1338.78
[000000000000001925] => 916
[000000000000002036] => 200.78
[000000000000001608] => 44341
)

PHP - How i can find a partial word in array?

I have a word:
$word = "samsung";
I have array:
$myarray = Array(
[0] => "Samsung=tv"
[1] => "Apple=mobile"
[2] => "Nokia=mobile"
[3] => "LG=tv"
I need now something like this to find a partial match:
if($word in $myarray){ echo "YES"; } // samsung found in Samsung=tv
Thank you for help.
You want in_array http://us3.php.net/manual/en/function.in-array.php.
if(in_array($word,$myarray){ echo 'yes'; }
Are you looking for something like this?
<?php
$myarray = array("Samsung=tv", "Apple=mobile", "Nokia=mobile", "LG=tv");
function findSimilarWordInArray($word, $array) {
if (empty($array) && !is_array($array) return false;
foreach ($array as $key=>$value) {
if (strpos( strtolower($value), strtolower($word)) !== false) {
return true;
} // if
} // foreach
}
// use case
if ( findSimilarWordInArray('samsung',$myarray) ) {
echo "I've found it!";
}
?>
It allows you to look for a similar word in array values.
If you are looking for partial matches, you can use strpos() with a foreach loop to iterate through the array.
foreach ($myarray as $key => $value) {
if (strpos($value, $word) !== FALSE) {
echo "Yes";
}
}
There is no built in function to do a partial match, but you can easily create your own:
function in_array_partial($needle, $haystack){
$result = false;
$needle = strtolower($needle);
foreach($haystack as $elem){
if(strpos(strtolower($elem), $needle) !== false){
$result = true;
break;
}
}
return $result;
}
Usage:
if(in_array_partial('samsung', $myarray)){
echo 'yes';
}
You can try something like this:
function my_in_array($word, $array){
forach($array as $value){
if(strpos($word, $value) !== false){
return true;
}
}
return false;
}

In CodeIgniter how can i pass an array type argument to a controller from url

//let my controller be C and method be:
function X($array){}
//And my url to call it is:
localhost/mysite/C/X/array
Well i tried it but it returns 400-Bad Request response.
Does anyone know how to do it? Quick response will help me a lot//Thanx
localhost/mysite/C/X/?array=1&&?array=2....
$array = $this->input->get('array');
or
localhost/mysite/C/X/1,2,3,4,5
$array = explode(',' $this->uri->segment(n));
// in app/config/config.php
$config['permitted_uri_chars'] = 'a-z 0-9~%.:,_-';
My variant for array in url (/tours/novogodniye-turi/visa=yes;duration=small;transport=4,7,6,2/)
if ( ! function_exists('filter_parse_segment'))
{
function filter_parse_segment($segment, $merge_to_get = FALSE)
{
if(empty($segment))
{
return FALSE;
}
$parameters = explode(";", (string)$segment);
if(empty($parameters))
{
return FALSE;
}
$parameters_array = array();
foreach($parameters as $parameter)
{
if(empty($parameter))
{
continue;
}
$parameter = explode("=", $parameter);
if( ! isset($parameter[0], $parameter[1]) or empty($parameter[0]))
{
continue;
}
if(strpos($parameter[1], ','))
{
$parameter[1] = explode(",", $parameter[1]);
}
$parameters_array[$parameter[0]] = $parameter[1];
}
if($merge_to_get === TRUE)
{
$_GET = array_merge($_GET, $parameters_array);
}
return $parameters_array;
}
}
// --------------------------------------------------------------------
if ( ! function_exists('filter_collect_segment'))
{
function filter_collect_segment($array, $suffix = '', $remove = array())
{
if(empty($array) || ! is_array($array))
{
return '';
}
$segment_str = '';
foreach ($array as $key => $value)
{
if(empty($key) || in_array($key, (array)$remove))
{
continue;
}
if( ! $segment_str == '')
{
$segment_str = $segment_str.';';
}
if( ! is_array($value))
{
$segment_str = $segment_str.$key.'='.$value;
continue;
}
if(empty($value))
{
continue;
}
$parsed_value = '';
foreach ($value as $item)
{
if( ! $parsed_value == '')
{
$parsed_value = $parsed_value.',';
}
if(is_array($item) || empty($item))
{
continue;
}
$parsed_value = $parsed_value.$item;
}
$segment_str = $segment_str.$key.'='.$parsed_value;
}
if($segment_str != '')
{
$segment_str = $segment_str.$suffix;
}
return $segment_str;
}
}
// --------------------------------------------------------------------
if ( ! function_exists('filter_key'))
{
function filter_key($filter_array, $key, $value = NULL)
{
if( ! isset($filter_array[$key]))
{
return;
}
if($value == NULL)
{
return $filter_array[$key];
}
if( ! is_array($filter_array[$key]) && $filter_array[$key] == (string)$value)
{
return $value;
}
if(is_array($filter_array[$key]) && in_array($value, $filter_array[$key]))
{
return $value;
}
return FALSE;
}
}
If you want the solution in the pretty nice URL then you have to loop the array first and then concatenate the elements with some - dash or + plus signs like this;
$array = array(1,2,3,4);
$string = "";
foreach($array as $value){
$string .= $value."-";
}
$string = rtrim($string, "-");
redirect(base_url()."get_products?param=".$string);
And on the next page just get the param and use explode() function with - dash sign to create the array again.
try your url like this
if value you have to pass is
[1,2,3,2]
then
localhost/mysite/index.php/C/X/1,2,3,2
In a simple way you can make the array a string with some special character in between the values of the array.
Then in the landing page you can split the string with the special character and get the array again.
If the values are [1,2,3,4], then make it using a loop "1,2,3,4".
Then pass the string.
In teh landing page split the string with "," and you will again get the array.
Hope it helps you.
Thanks
Why don't you use uri segments for array? You can count uri segments and could use them. Even u could check how many arrays already there.
url.com/1/2/3
http://ellislab.com/codeigniter/user-guide/libraries/uri.html
Note: uri segment doesnt work on main controller index function, you have to define another function than index for example: I don't know what it happens but i think because of htaccess file I'm using do remove index.php.
url.com/uri_segment_controller/go/1/2/3

How to get hierarchy path of an element in an Array

I always want to get the exact path of an element in an array.
Example array:
array(a=>'aaa', 'b'=> array ('bbb1', 'bbb2' => array('bbb3', 'bbb4')));
So, for reaching to 'bbb4', I need to go through (b => bbb2 => bbb4).
How to get this path in multidimensional array?
function get_from_array($toBeSearchedArray , $searchValue , &$exactPath)
{
foreach($toBeSearchedArray as $key=>$value)
{
if(is_array($value) && count($value) > 0)
{
$found = get_from_array($value , $searchValue , $exactPath);
if($found)
{
$exactPath = $key."=>".$exactPath;
return TRUE;
}
}
if($value == $searchValue)
{
$exactPath = $value;
return true;
}
}
return false;
}
$exactPath = "";
$argArray = array('a'=>'aaa', 'b'=> array ('bbb1', 'bbb2' => array('bbb3', 'bbb4')));
get_from_array($argArray , "bbb4" , $exactPath);
echo $exactPath;

How to check if a certain part of the array exists in another array?

I have an two associative arrayes and I want to check if
$array1["foo"]["bar"]["baz"] exists in $array2["foo"]["bar"]["baz"]
The values doesn't matter, just the "path".
Does array_ intersect_ assoc do what I need?
If not how can I write one myself?
Try this:
<?php
function array_path_exists(&$array, $path, $separator = '/')
{
$a =& $array;
$paths = explode($separator, $path);
$i = 0;
foreach ($paths as $p) {
if (isset($a[$p])) {
if ($i == count($paths) - 1) {
return TRUE;
}
elseif(is_array($a[$p])) {
$a =& $a[$p];
}
else {
return FALSE;
}
}
else {
return FALSE;
}
$i++;
}
}
// Test
$test = array(
'foo' => array(
'bar' => array(
'baz' => 1
)
),
'bar' => 1
);
echo array_path_exists($test, 'foo/bar/baz');
?>
If you only need to check if the keys exist you could use a simple if statement.
<?php
if (isset($array1["foo"]["bar"]["baz"]) && isset($array2["foo"]["bar"]["baz"]
)) {
//exists
}

Categories