PHP searching multidimensional array for item - php

I currently have an array set up like this:
$u_id= array(
array(
NUM=>'2770', DESC=>'description one'
),
array(
NUM=>'33356', DESC=>'description two'
),
array(
NUM=>'13576', DESC=>'description three'
),
array(
NUM=>'14141', DESC=>'description four'
)
);
I need to be able to pass a number through this array as $num (corresponding to a NUM=>'' in the array), and store the corresponding DESC=>'' as a string. For example, searching for "2770" would return "description one".
What would be the best way to go about doing this?

Are you constrained to this array structure? Because a more efficient structure would be to just do
$u_id= array(
'2770' => 'description one',
'33356' => 'description two',
'13576' => 'description three',
'14141' => 'description four'
);
That is to say, you just assume that the key is the number and the value is the description, rather than naming them explicitly. Then the code to find the correct description is just $u_id[2770] (or whichever).
If that's not acceptable, you could also do
$u_id= array(
'2770' => array(
NUM=>'2770', DESC=>'description one'
),
'33356' => array(
NUM=>'33356', DESC=>'description two'
),
'13576' => array(
NUM=>'13576', DESC=>'description three'
),
'14141' => array(
NUM=>'14141', DESC=>'description four'
)
);
That is, the number is also used as the key to find the correct pair. The code to find the correct description becomes $u_id[2770]["NUM"].
In either of these scenarios, finding a given description from the number is a single step. If you can't change the array structure, though, then you'd have to loop through the array to check (which could take as many steps as there are items in the array).

foreach($arrays as $arr){
if($arr['NUM']==$num){
return $arr['DESC'];
}
}

Related

How to loop through a list of products and categories on PHP

<?
$categoriesID = array("popular","old");
$product => array (
Product 1
'categoryID' => $categoriesID[1],
'Name' => 'Product One',
Product 2
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
Product 3
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
Product 4
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
);
How can I loop through this to reflect that product 1 belongs to category 1, product 2 belongs to category 2, product 3 belongs to category 2 and so on?
I tried the following but no luck..
foreach($product as $key => $pro){
var_dump($categoriesID[$key]);
}
I would really appreciated any suggestions or how what i'm doing wrong.The goal is to insert the relationship into a database table where in order to insert a product a category_id is required.
Your arrays are not written correctly. You got a multi dimensional array here (arrays inside of an array). Read this to understand how they are written and how you can work with them: http://php.net/manual/en/language.types.array.php
If your categories are numeric you should also consider to use numeric values: 1 instead of '1' inside of the $categoriesID array or depending on the database auto casting capability you will get issues inserting strings as decimals.
Here is your given code modified as working example. Ive changed the var_dump output for better readability of the result.
Ive also changed the array indexes you have used since arrays start at 0. If you need the numbers still to start at 1 you could add some nonsense value at the beginning of the array or subtract 1 when accessing the array. Keep in mind that this is an quick & dirty solution to the given problem.
Nevertheless as Patrick Q said you should consider some introduction to PHP.
<?php
$categoriesID = array('1','2');
$product = array (
array(
'categoryID' => $categoriesID[0],
'Name' => 'Product One',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
)
);
foreach($product as $key => $value){
echo var_export($value, true) . '<br>';
}
You could further edit Mariusz's answer to do something like this:
foreach($product as $item){
echo $item['Name'].' - '.$item['categoryID'].'<br>';
}
This would give you easy access to both product name and category ID.

Merge multidimensional array in PHP

I have a multi array and I need to combine it with other. This array is made for send in XML format to SOAP, so it need to have the correct structure.
This array is like an invoice, it have "items" which i have to repeat. So, i think in make two arrays (one have always the same structure) and add the items array.
The problem is that if I use merge, I could not put the second array in the correct key. Here an example.
This is the correct array structure:
$params = array(
'authRequest' =>
array( 'token' => 'token',
'sign' => 'sign',
'cuitRepresentada' => 'CUIT' ),
'comprobanteRequest' =>
array( 'codigoTipoComprobante' => $codtipcbte,
'numeroPuntoVenta' => $ptovta,
'numeroComprobante' => $cbte,
**'arrayItems' =>
array( 'item' =>
array(
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
),
),**
'arraySubtotalesIVA' =>
array( 'subtotalIVA' =>
array(
'codigo'=> $compreqiva['codIva'],
'importe'=> $compreqiva['importe'],
),
),
),
);
So, i build the array with "arrayItems" empty
'arrayItems' => array(),
Then i build the arrayItem array:
$arrayitems =
array('arrayItems' =>
array( 'item' =>
array(
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
),
),
);
Then i use merge to join both array:
$resultado = array_merge($params['comprobanteRequest'], $arrayitems);
Works, but the first key is deleted...
'authRequest' =>
array( 'token' => 'token',
'sign' => 'sign',
'cuitRepresentada' => 'CUIT' ),
I dont know why is deleted, maybe the merge function is not the corect way...
Thanks in advance!
If in your first array, arrayItems is always empty, then you don't need a merge, just set the value :
$params['comprobanteRequest']['arrayItems'] = $arrayItems['arrayItems'];
Of course this can be simplified, since $arrayItems contains only one key, but you get the spirit.

Scoring results, then sorting it to show much relevant result

I'm working on trying to figure out how to show a search result from closest match to least closest.
Let's assume this is the multidimensional array of results. You will notice that there are arrays with the same "id", but have different "categories". I'm pretending this is a one-to-many relationship. So I'm assuming, for 1 "id", a user might have tagged it to 3 different relevant categories.
$results[] = array(
'id' => 1 ,
'text' => 'this is my first post',
'category' => 'blue'
);
$results[] = array(
'id' => 1 ,
'text' => 'this is my first post',
'category' => 'green'
);
$results[] = array(
'id' => 1 ,
'text' => 'this is my first post',
'category' => 'purple'
);
$results[] = array(
'id' => 2 ,
'text' => 'this is my second post',
'category' => 'blue'
);
$results[] = array(
'id' => 2 ,
'text' => 'this is my second post',
'category' => 'green'
);
Now, let's assume there are criteria that the user selected. I'll show it in array form:
$criterias = array('blue', 'green', 'purple');
Using this example, that means the $results "id" of 1 should show up first, and I want to show it's "text". This is because it scored 3 out of 3 (based on matching the criteria that was set in $criterias). Then following this logic the $results "id" of 2 should show up second because it only scored a 2 out of 3.
The final form what what I'm looking to do is be able to echo out the "text" value from highest score to lowest.
My level of programming in PHP is intermediate, so if you could please demonstrate a less complex solution that an intermediate could understand that would be great.
What I tried and didn't get to work was trying to first try to score it and put it into another multidimensional array and sort it, then echo it, but I couldn't get it to work.

Recursively merge two arrays, or replace with latter based on a key

This should be a really easy answer and I'm probably just being thick, but I have two arrays in PHP:
$data1 = array(
array(
'qid' => 'q-prof-1-1',
'value' => 10,
),
array(
'qid' => 'q-prof-2-1',
'value' => 3,
),
);
$data2 = array(
array(
'qid' => 'q-prof-2-1',
'value' => 5,
),
array(
'qid' => 'q-prof-3-2',
'value' => 1,
),
);
And I want to result in:
$result = array(
array(
'qid' => 'q-prof-1-1',
'value' => 10,
),
array(
'qid' => 'q-prof-2-1',
'value' => 5,
),
array(
'qid' => 'q-prof-3-2',
'value' => 1,
),
);
... so that the two will be merged- but, if it finds a qid that matches another, will replace it with the latter.
I've tried a mixture of array_merge(), array_merge_recursive(), $data1 + $data2, $data2 + $data1, array_replace(), array_replace_recursive(), array_diff() etc, etc, but every options seems to return either two or four values rather than the three. And of course I've done my fair share of S.O hunting.
Any ideas? Would prefer something short and sweet to a massive iterating function of any sort!
Thanks in advance :)
Matt
Edit:
I've just realised that if I turn the arrays inside $data1 & $data2 into key-value pairs most of those merge and replace functions work, eg:
$data1 = array(
'q-prof-1-1' => array(
'qid' => 'q-prof-1-1',
'value' => 10,
) // ... etc etc
);
... but I'd still rather not have to change the original data
Is there a reason you can't use an associative array? That way you can just have
$array = array('q-prof-1-1' => 10, 'q-prof-2-1' => 3);
$array2 = array('q-prof-2-1' => 5, 'q-prof-3-2' => 1);
Then just loop through $array2, push the value on if $array doesn't have a key (key_exists() if i remember right) or if it does have a key merge them how you want?
Also, but not sure, using an associative array would probably make array_merge work correctly (possibly).

Applying a custom order to a multi-dimensional array

I have this array
$arr = array(
'one' => array(
'slidertitle' => 'lorem ipsum',
'sliderlocation' => 'http://localhost/images/1.jpg',
'sliderdescription' => 'this is a good lorem ipsum image',
'sliderposition' => 1
),
'two' => array(
'slidertitle' => 'second slider',
'sliderlocation' => 'http://localhost/images/2.jpg',
'sliderdescription' => 'this space was reserved for a link source code here',
'sliderposition' => 2
),
'six' => array(
'slidertitle' => 'sixth slider',
'sliderlocation' => 'http://localhost/images/6.jpg',
'sliderdescription' => 'this is the sixth slider,like,really!',
'sliderposition' => 6
)
);
which i need to look like this
$arr = array(
'two' => array(
'slidertitle' => 'second slider',
'sliderlocation' => 'http://localhost/images/2.jpg',
'sliderdescription' => 'this space was reserved for a link source code here',
'sliderposition' => 2
),
'six' => array(
'slidertitle' => 'sixth slider',
'sliderlocation' => 'http://localhost/images/6.jpg',
'sliderdescription' => 'this is the sixth slider,like,really!',
'sliderposition' => 6
),
'one' => array(
'slidertitle' => 'lorem ipsum',
'sliderlocation' => 'http://localhost/images/1.jpg',
'sliderdescription' => 'this is a good lorem ipsum image',
'sliderposition' => 1
)
);
I am attempting to do that by defining the expected array structure and introducing a dummy array.I then chunk the array and merge each chunk to the array format and i plan to finally unset the dummy and i am left with the array i want and in the order i want.
$arrayFormat = array(
'dummy' => array(
'slidertitle' => 'xxxx',
'sliderlocation' => 'xxxxxxx',
'sliderdescription' => 'xxxxxx',
'sliderposition' => 0
)
);
$arrayLength = count($arr);
$afterChunk = array_chunk($arr,$arrayLength);
$one = $afterChunk[0][0];
$two = $afterChunk[0][1];
$mergedArray = array_merge($arrayFormat,$one);
$secondMergedArray = array_merge($mergedArray,$two);
echo '<pre>';
print_r($secondMergedArray);
echo '</pre>';
The problem is array_chunk() does not include the key of the array so i am getting
Array (
[dummy] => Array
(
[slidertitle] => xxxx
[sliderlocation] => xxxxxxx
[sliderdescription] => xxxxxx
[sliderposition] => 0
)
[slidertitle] => second slider
[sliderlocation] => http://localhost/images/2.jpg
[sliderdescription] => this space was reserved for a link source code here
[sliderposition] => 2 )
when i print_r($secondMergedArray);.is there something that can be done to array_chunk() to include the array key or is there any other array function that can help me get individual array inclusive of the key?.
It's really hard to tell what you're wanting in terms of how to sort the elements. You've not been very clear in the question. There has to be something in the array that you know what order it needs to be.
In the absence of any clues as to what that is, I'm going to assume you want to specify the order of the array keys manually.
So, the current array is array('one'=>... , 'two'=>... , 'six'=>... ) and you want to sort those keys in an order you want to specify manually.
The solution is to use the uksort() function, along with a separate array specifying your sort order:
$arr = ... //input array as specified in the question
$sortOrder = array('two','one','six');
uksort($arr, function ($a, $b) use ($sortOrder) {
$sortMe = array_flip($sortOrder);
if ($sortMe[$a] == $sortMe[$b]) { return 0; }
return ($sortMe[$a] < $sortMe[$b]) ? -1 : 1;
});
print_r($arr);
Outputs your array in 'two','one','six' order. Change the $sortOrder array as required.
Hope that helps.
Note: the syntax I've provided above only works in PHP 5.3 and above. (if you're using an older version, you need to upgrade)
use uksort() for custom order for multidimensional array
http://php.net/manual/en/function.uksort.php

Categories