How to extract data out of a specific PHP array

后端 未结 3 1792
梦如初夏
梦如初夏 2021-01-28 07:02

I have a multi-dimensional array that looks like this: The base array is indexed based on category ids from my catalog.

$cat[category_id]

Ea

3条回答
  •  面向向阳花
    2021-01-28 07:25

    Assuming it's something of this sort:

    $ary = Array(
      0 => Array(
        'parent_category_id' => null,
        'sort_order' => 0,
        'name' => 'my-category-name0'
      ),
      1 => Array(
        'parent_category_id' => 0,
        'sort_order' => 1,
        'name' => 'my-category-name1'
      ),
      2 => Array(
        'parent_category_id' => 0,
        'sort_order' => 2,
        'name' => 'my-category-name2'
      ),
      3 => Array(
        'parent_category_id' => null,
        'sort_order' => 0,
        'name' => 'my-category-name3'
      ),
      4 => Array(
        'parent_category_id' => 3,
        'sort_order' => 0,
        'name' => 'my-category-name4'
      )
    );
    

    You can use a combination of a foreach and usort to achieve what you're going for.

    // @array: the array you're searchign through
    // @parent_id: the parent id you're filtering by
    function getFromParent($array, $parent_id){
      $result = Array();
      foreach ($array as $category_id => $entry){
        if ($entry['parent_category_id']===$parent_id)
          $result[$category_id] = $entry;
      }
      usort($result,create_function('$a,$b','return ($a["sort_order"]>$b["sort_order"]?1:($b["sort_order"]<$a["sort_order"]?-1:0));'));
      return $result;
    }
    
    var_export(getFromParent($ary,0));
    

    EDIT Sorry, fixed some syntax errors. Tested, and works (at least to result in what I was intending)
    EDITv2 Here's the raw output from the above:

    array (
      0 => 
      array (
        'parent_category_id' => 0,
        'sort_order' => 1,
        'name' => 'my-category-name1',
      ),
      1 => 
      array (
        'parent_category_id' => 0,
        'sort_order' => 2,
        'name' => 'my-category-name2',
      ),
    )
    

    (Used var_export just for you @FelixKling)

    EDITv3 I've updated my answer to go along with the OP's update. I also now make it retain the original "category_id" values in the result array.

提交回复
热议问题