I have a multidimensional array like this which I converted from JSON:
Array (
[1] => Array (
[name] => Test
[id] => [1]
)
[2] => Array (
[name] => Hello
[id] => [2]
)
)
How can I return the value of id if name is equal to the one the user provided? (e.g if the user typed "Test", I want it to return "1")
Edit: Here's the code that works if anyone wants it:
$array = json_decode(file_get_contents("json.json"), true);
foreach($array as $item) {
if($item["name"] == "Test")
echo $item["id"];
}
The classical solution is to simply iterate over the array with foreach and check the name of each row. When it matches your search term you have found the id you are looking for, so break to stop searching and do something with that value.
If you are using PHP 5.5, a convenient solution that works well with less-than-huge data sets would be to use array_column:
$indexed = array_column($data, 'id', 'name');
echo $indexed['Test']; // 1
You can use this function
function searchObject($value,$index,$array) {
foreach ($array as $key => $val) {
if ($val[$index] === $value)
return $val;
}
return null;
}
$MyObject= searchObject("Hello","name",$MyArray);
$id = $MyObject["id"];
You can do it manually like, in some function:
function find($items, $something){
foreach($items as $item)
{
if ($item["name"] === $something)
return $item["id"];
}
return false;
}
here is the solution
$count = count($array);
$name = $_POST['name']; //the name which user provided
for($i=1;$i<=$count;$i++)
{
if($array[$i]['name']==$name)
{
echo $i;
break;
}
}
enjoy
Try this:
$name = "Test";
foreach($your_array as $arr){
if($arr['name'] == $name){
echo $arr['id'];
}
}
Related
I have an array like below
Array
(
[0] => country-indonesia
[1] => country-myanmar
[2] => access-is_airport
[3] => heritage-is_seagypsy
)
From that array I want to make separate array only for [country] ,[access], [heritage]
So for that I have to check array value by text before '-'. I am not sure how to do it. so i can't apply code here. I just have the array in PHP
A modified answer, if you want to get the specific types only.
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
$types = ['country', 'heritage', 'access'];
foreach ($arr as $element) {
$fac = explode('-', $element);
foreach ($types as $type) {
if ($fac[0] === $type) {
$new_array[$type][] = $fac[1];
}
}
}
$country = $new_array['country'];
$access = $new_array['access'];
$heritage = $new_array['heritage'];
var_dump($new_array);
A simple and easy solution in 3 lines of code using array_walk
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
array_walk($arr, function($item) use (&$new_array){
//if(false === strpos($item, '-')) return;
list($key,$value) = explode('-', $item, 2);
$new_array[$key][] = $value;
});
print_r($new_array);
Gives this output:
Array
(
[country] => Array
(
[0] => indonesia
[1] => myanmar
)
[access] => Array
(
[0] => is_airport
)
[heritage] => Array
(
[0] => is_seagypsy
)
)
If you don't want empty and duplicate entries:
<?php
$arr = [
'country-indonesia',
'country-myanmar',
'access-is_airport',
'heritage-is_seagypsy',
];
$new_array = [];
array_walk($arr, function($item) use (&$new_array){
if(false === strpos($item, '-')) return;
list($key,$value) = explode('-', $item, 2);
if(empty($value) || array_key_exists($key, $new_array) && in_array($value, $new_array[$key])) return;
$new_array[$key][] = $value;
});
print_r($new_array);
you can do it by using explode and in_array functions
<?php
$arr = ["country-indonesia","country-myanmar","access-is_airport","heritage-is_seagypsy"];
$newArr = array();
foreach($arr as $k=> $val){
$valArr = explode("-", $val);
if(!in_array($valArr[0], $newArr)){
$newArr[] = $valArr[0];
}
}
print_r($newArr);
?>
live demo
You need PHP's strpos() function.
Just loop through every element of the array and try something like:
if( strpos($array[$i], "heritage") != false )
{
// Found heritage, do something with it
}
(Rough example written from my cellphone while feeding baby, may have typos but it's the basics of what you need)
Read further here: http://php.net/manual/en/function.strpos.php
//first lets set a variable equal to our array for ease in working with i.e
// also create a new empty array to hold our filtered values
$countryArray = array();
$accessArray = array();
$heritageArray = array();
$oldArray = Array(country-indonesia, country-myanmar, access-is_airport, heritage-is_seagypsy);
//Next loop through our array i.e
for($x = 0; $x < count($oldArray); $x++){
// now filter through the array contents
$currentValue = $oldArray[$x];
// check whether the current index has any of the strings in it [country] ,[access], [heritage] using the method : strpos()
if(strpos($currentValue,'country')){
//if this particular value contains the keyword push it into our new country array //using the array_push() function.
array_push($countryArray,$currentValue);
}elseif(strpos($currentValue,'access')){
// else check for the access string in our current value
// once it's found the current value will be pushed to the $accessArray
array_push($accessArray,$currentValue);
}elseif(strpos($currentValue,'heritage')){
// check for the last string value i.e access. If found this too should be pushed to //the new heritage array i.e
array_push($heritageArray,$currentValue);
}else{
// do nothing
}
}
//I believe that should work: cheers hope
I have array like this
$arr=[["a","b"],["b","c"],["d","e"],["f","c"]];
if sub arrays share same value they should be be merged to one array
expected output:
$arr=[["a","b","c","f"],["d","e"]];
I`m trying to avoid doing foreach inside foreach for solving this.
It seems your inner arrays always have 2 items. so nested loops aren't necessary. Here is a solution which I originally wrote in JS but it should work just as good and most efficient in PHP:
$arr=[["a","b"],["b","c"],["d","e"],["f","c"],["h","e"]];
$output = [];
$outputKeys = [];
$counter = 0;
foreach($arr as $V) {
if(!isset($outputKeys[$V[0]]) && !isset($outputKeys[$V[1]])) {
$output[$counter] = [$V[0], $V[1]];
$outputKeys[$V[0]] = &$output[$counter];
$outputKeys[$V[1]] = &$output[$counter];
$counter++;
}
elseif(isset($outputKeys[$V[0]]) && !isset($outputKeys[$V[1]])) {
array_push($outputKeys[$V[0]], $V[1]);
$outputKeys[$V[1]] = &$outputKeys[$V[0]];
}
elseif(!isset($outputKeys[$V[0]]) && isset($outputKeys[$V[1]])) {
array_push($outputKeys[$V[1]], $V[0]);
$outputKeys[$V[0]] = &$outputKeys[$V[1]];
}
}
var_dump($output); // [["a","b","c","f"],["d","e","h"]]
DEMO (click the execute button)
Pointers are your friends. Use them :)
The following algorithm should do what you want. It simply checks through each item and checks if it already exists in the newly created array, and if it does it adds it to that item instead of a new one:
<?php
$arr=[["a","b"],["b","c"],["d","e"],["f","c"]];
$newArr = [];
foreach ($arr as $items) {
$newKey = null;
foreach ($items as $item) {
foreach ($newArr as $newItemsKey => $newItems) {
if (in_array($item, $newItems)) {
$newKey = $newItemsKey;
break 2;
}
}
}
if ($newKey !== null) {
$newArr[$newKey] = array_merge($newArr[$newKey], $items);
} else {
$newArr[] = $items;
}
}
$newArr = array_map('array_unique', $newArr);
print_r($newArr);
Output:
Array
(
[0] => Array
(
[0] => a
[1] => b
[3] => c
[4] => f
)
[1] => Array
(
[0] => d
[1] => e
)
)
DEMO
This is solution I get for now.
$arr=[["a","b","c","f"],["d","e"]];
$sortedArray = sortFunction($arr,0,array());
function sortFunction($old,$index,$new) {
if ($index == sizeof($old)) return $new;
for ($i = 0; $i<sizeof($new); $i++) {
if (count(array_intersect($new[$i],$old[$index]))) {
$new[$i] = array_unique(array_merge($old[$index],$new[$i]), SORT_REGULAR);
return sortFunction($old,$index + 1,$new);
}
}
$new[] = $old[$index];
return sortFunction($old,$index + 1,$new);
}
Ok I'm seriously stuck, I've been working on a nav menu that I just cannot get to function how I want it to so i've changed tack but am now stuck again so any help would be much appreciated and desperately needed!
I have the code below and am trying to do the following - I have an array that holds info for all the pages of a site and then another array that holds the ids of the pages that are child pages. What I want to do is use a foreach loop to loop through all the pages of the first array and check whether their ids are in the array of child ids or not. If they are not then they are top level nav pages and I want to output some code and then set up another foreach loop which will check whether any subpages have a parent id of the current page and so on.
I can't seem to work out how to compare $b with the ids in the $childpages array no matter what I try! Is this even possible and if so how please?
This is the first section of what im trying at present
<?php function buildMenu4 ($allpages, $childpages) {
foreach ($allpages as $pages){
$a = $pages['parentid'];
$b = $pages['id'];
$c = $childpages;
echo "<ul>\n";
if (!in_array($b, $c)) {
DO SOMETHING..........
Array contents of $c:
Array
(
[0] => Array ( [id] => 6 )
[1] => Array ( [id] => 15 )
[2] => Array ( [id] => 100 )
[3] => Array ( [id] => 101 )
[4] => Array ( [id] => 103 )
[5] => Array ( [id] => 104 )
[6] => Array ( [id] => 105 )
)
edit ---------------------------------
I have reworked my code and am back to a variation of where I was a couple of days ago!! Anyway the code below works as intended until I try to loop it and then it just echoes the results of the first foreach loop e.g. foreach ($allpages as $pages){..... but fails to do anything else.
I am trying to make a function called loopMenu and then run this recursively until there are no more pages to be displayed. I have tried to write the function as shown with the pusedo code in the code block below but I just can't get it to work. I may have muddled up some of the arguments or parameters or perhaps I have just made a big mistake somewhere but I can't see it - any help would be hugely appreciated and desperately needed!
<?php function buildMenu6 ($allpages, $childpageids, $childpages, $subchildpages) {
foreach ($childpageids as $childid){
$c[] = $childid['id'];
};
echo "<ul>\n";
foreach ($allpages as $pages){
$a = $pages['parentid'];
$b = $pages['id'];
if (!in_array($b, $c)){
echo "<li>" . $pages['linklabel'] . "";
WHERE I WANT THE FUNCTION TO START E.G. function loopMenu($childpages, $subchildpages){...the code that follows....
echo"<ul>\n";
foreach ($childpages as $childparent) {
$d = $childparent['parentid'];
$e = $childparent['id'];
if (($d == $b) or ($d == $g)) {
echo "<li>" . $childparent['linklabel'] . "";
echo "<ul>\n";
foreach ($subchildpages as $subchild){
$g = $subchild['id'];
$f = $subchild['parentid'];
if ($f == $e){
echo "<li>" . $subchild['linklabel'] . "";
WHERE I TRY TO RERUN THE FUNCTION USING loopMenu($childparent, $subchild);
echo "<li/>";
};
};
echo"</ul>\n";
echo "</li>";
};
};
echo "</ul>\n";
WHERE I WANT MY FUNCTION TO END E.G. };
echo "</li>";
};
};
echo "</ul>\n";
}; ?>
Then I call the main buildMenu6 function like so:
<?php buildMenu6($pageids, $childPageIds, $childPageArray, $childPageArray); ?>
You need a nested foreach (I've changed your var names or used the original ones for readability):
foreach($allpages as $page) {
foreach($childpages as $child) {
if($page['id'] == $child['id']) {
//do something
break;
}
}
}
Or PHP >= 5.5.0 use array_column:
$childids = array_column($childpages, 'id');
foreach($allpages as $page) {
if(in_array($page['id'], $childids)) {
//do something
}
}
As a kind of hybrid:
foreach($childpages as $child) {
$childids[] = $child['id'];
}
foreach($allpages as $page) {
if(in_array($page['id'], $childids)) {
//do something
}
}
foreach ($allpages as $pages){
$a = $pages['parentid'];
$b = $pages['id'];
$c = $childpages;
echo "<ul>\n";
// In array isn't aware of the 'id' keys
$found = false;
foreach ($c as $id => $value) {
if ($value == $b) {
$found = true;
}
}
if ($found) {
// DO SOMETHING
}
according to THIS SO ANSWER, array_key_exists is (marginally) the fastest array lookup for php.
since, from your description, it seems reasonable to suppose that [id] is a PRIMARY key and, therefore, unique, i would change the [id] dimension and put values directly in its lieu:
$c[105] = NULL; // or include some value, link page URL
... // some code
$needle = 105;
... // some more code
if (array_key_exists($needle,$c)) {
instead of
$c[5] = 105; // $c is the haystack
... // some code
$needle = 105;
... // some more code
foreach ($c as $tempValue) {
if ($tempValue == $needle) {
in case you want to put values in $c, then you could also use isset (it will return FALSE if array value is NULL for said key).
i want so replace something in a array, but the array isn´t sorted. So maybe you know how i can fix the problem.
I´ve a array with a few of this element.
<media type="image" id="image5" label="book5.jpg" group="image" source="list2/Schuh2.jpg" url="image5/0.jpg" icon="image5/0.jpg"/>
How can i sort the array by the value of lable? so that first i get for example from
Lables:
book3
book4
book2
-->
book2
book3
book4
i hope you know what i mean :D thank you ;-)
$books = array('book3', 'book4', 'book2');
sort($books);
or
$books = array('label1' =>'book5.jpg',
'label2' => 'book4.jpg', 'label3' => 'book3.jpeg');
asort($books); // sorts by value (ascending)
hope this helps!
Hack
foreach($a as $k => $media) {
$parts = explode(' ',$media);
foreach($parts as $part) {
$kv = explode('=', $part);
if ($kv[0] == 'label') {
$a[$kv[1]] = $media;
unset($a[$k]);
}
}
}
ksort($a);
or look at usort() which let you use your own comparison function
Assuming unique book#.jpg images you could do something like ...
<?php
$sortedArray = array();
foreach ($unsortedArray as $item ) {
$sortedArray[explode('.', explode('label="book', $item)[1])[0]] = $item;
}
ksort($sortedArray);
foreach ($sortedArray as $item ) {
echo $item;
}
?>
I did not test this.
UPDATE:
Someone else's suggestion to use usort() is a good one. Something like this ...
<?php
function compareElements($a, $b) {
$aNum = explode('.', explode('label="book', $a)[1])[0];
$aNum = explode('.', explode('label="book', $b)[1])[0];
return ($aNum < $bNum) ? -1 : 1;
}
usort($arrayOfElements, "compareElements");
foreach ($arrayOfElements as $element) {
echo $element;
}
?>
The Problem was, that i can´t sorte bei the one value ['id'] so i has create me one array with all the Informations, and a second only with the ['id'] of the pictures.
Input and load the XML-File.
$mashTemplateFile = 'C:\Users\...\test.xml';
$mashTemplate = simplexml_load_file($mashTemplateFile);
$mash = $mashTemplate->mash;
declare the arry's
$imageArrayMedTemp = array();
$imageArrayMedID = array();
$imageArrayMed = array();
put all the information from the media in the array $imageArrayMedTemp and only the ['id']into the array $imageArrayMedID.
foreach ($mash->media as $med) {
if ($med['type'] == 'image') {
array_push($imageArrayMedTemp , $med);
array_push($imageArrayMedID , $med['id']);
}
now i sort the array with the ['id']'s
natsort($imageArrayMedID);
after sorting i will put the information from the array $imageArrayMedTemp into a new array $imageArrayMed, storing by when the key of both is the same.
foreach ($imageArrayMedID as $key1 => $value1) {
foreach ($imageArrayMedTemp as $key2 => $value2) {
if($key1 == $key2){
array_push($imageArrayMed,$value2);
}
}
}
I have the following code:
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$array_30 = array
(
'0'=>1,
1=>'2',
2=>'3'
);
$array_31 = array
(
'0'=>4,
'1'=>'5',
'2'=>'6'
);
I need to make it an array and insert the array_30 and array_31 into a DB.
foreach($rt1 as $value){
$rt2[] = $value['0'];
}
The question was updated, so here is an updated answer. Quick check, you should really try and update this to whatever more generic purpose you have, but as a proof of concept, a runnable example:
<?php
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$finalArrays = array();
foreach($rt1 as $key=>$value){
if(is_array($value)){
$array_name = "array_".substr($key,-2);
${$array_name}[] = $value['0'];
}
}
var_dump($array_30);
var_dump($array_31);
?>
will output the two arrays with the numbers 1,2,3 and 4,5,6 respectivily
i assume you want to join the values of each of the second-level arrays, in which case:
$result = array();
foreach ($rt1 as $arr) {
foreach ($arr as $item) {
$result[] = $item;
}
}
Inspired by Nanne (which reminded me of dynamically naming variables), this solution will work with every identifier after the \#, regardless of its length:
foreach ( $rt1 as $key => $value )
{
if ( false == strpos($key, '#') ) // skip keys without #
{
continue;
}
// the part after the # is our identity
list(,$identity) = explode('#', $key);
${'array_'.$identity}[] = $rt1[$key]['0'];
}
Presuming that this is your actual code, probably you will need to copy the array somewhere using foreach and afterwards create the new array as you wish:
foreach($arr as $key => $value) {
$arr[$key] = 1;
}