-1

I have a JSON record I converted to a PHP array.

$db=array(
  array("Name"=>"Beans","Price"=>"10"),
  array("Name"=>"Salad","Price"=>"5"),
  array("Name"=>"Bread","Price"=>"2"),
  array("Name"=>"Lime","Price"=>"1")
);

The real table of data is this.

Index   Name    Price
0       Beans   10
1       Salad   5
2       Bread   2
3       Lime    1

When I want to retrieve the first item name, I can easily do it like this:

$item=$db[0]['Name'];

That's until I decide to sort the array by a column like so:

array_multisort(array_column($db,'Price'),$db);

Then PHP thinks of the array this way:

$db=array(
  array("Name"=>"Lime","Price"=>"1"),
  array("Name"=>"Bread","Price"=>"2"),
  array("Name"=>"Salad","Price"=>"5"),
  array("Name"=>"Beans","Price"=>"10"),
);

Which completely messes the internal indexing because now:

$item=$db[0]['Name'];

equals 'Lime'

Is there a way to retrieve the previous index before the sorting so I can still reference the records properly.

For example, can I somehow use sorting functions to turn:

$db=array(
  array("Name"=>"Beans","Price"=>"10"),
  array("Name"=>"Salad","Price"=>"5"),
  array("Name"=>"Bread","Price"=>"2"),
  array("Name"=>"Lime","Price"=>"1")
);

to something like:

$db=array(
  array("Name"=>"Lime","Price"=>"1","index"=>3),
  array("Name"=>"Lime","Price"=>"1","index"=>2),
  array("Name"=>"Salad","Price"=>"5","index"=>1),
  array("Name"=>"Beans","Price"=>"10","index"=>0),
);

but here, index will be automatically added to the array then my program can reference that when editing the correct information. Ideas?

1
  • I'd use array_map and usort. Commented Jan 11 at 22:02

1 Answer 1

0

If you are looking to find a specific item by name in the array, regardless of whether it has been searched, you use:

  • array_column to establish a list of Names based on the object array
  • array_search to provide the index
  • use the array index on the original array to get the actual object

Code Here

$i = array_search("Lime", array_column($db, 'Name'));
$element = ($i !== false ? $db[$i] : null);
echo $element["Name"]; 
echo $element["Price"];

Note that array_column and array_search need to be performed after your sort to have the correct index associated with the sorted array.

In this case, I'm using the Name property to produce an array and then searching for the text "Lime". The second line returns a null if the text wasn't found in the Name array, or the particular item. The other lines are just proof it's functional and can be excluded.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.